例子来源:http://spring.io/guides/gs/relational-data-access/
使用java spring对数据库进行操作,使用了spring官网的例子,用JdbcTemplate这个裸写sql的方法,没有用hibernate或者myibatis.
spring官网的例子使用h2一个内置的内存数据库,没有配置文件生成为对象的烦恼,
为了练习下yaml替代xml,使用了如下的mysql jdbc配置,application.yaml.
### application.yaml ### mysql config spring: datasource: dbcp: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://192.168.18.129:3306/test1 username: root password: 123456
找了半天自动将依赖注入为一个JdbcTemplate对象,也没有搞定,就只好像下面一样自己先生成DataSource,再new一个JdbcTemlate对象,最后使用jdbcTemplate对数据库进行操作,这样写的很丑,希望各位可以指点一下。
@Bean @ConfigurationProperties(prefix = "spring.datasource.dbcp") public DataSource mysqlSource() { return DataSourceBuilder.create().build(); } @Bean public JdbcTemplate mysqlJdbcTemplate() { return new JdbcTemplate(mysqlSource()); }
下面是对数据库的一些CRUD操作,使用jdk8的函数式编程:
JdbcTemplate jdbcTemplate = mysqlJdbcTemplate(); jdbcTemplate.execute("DROP TABLE IF EXISTS customers"); jdbcTemplate.execute("CREATE TABLE customers(" + "id SERIAL, first_name VARCHAR(255), last_name VARCHAR(255))"); // Split up the array of whole names into an array of first/last names List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long") .stream() .map(name -> name.split(" ")) .collect(Collectors.toList()); // Use a Java 8 stream to print out each tuple of the list splitUpNames.forEach(name -> log.info(String.format("Inserting customer record for %s %s", name[0], name[1]))); // Uses JdbcTemplate's batchUpdate operation to bulk load data jdbcTemplate.batchUpdate("INSERT INTO customers(first_name, last_name) VALUES (?,?)", splitUpNames); log.info("Querying for customer records where first_name = 'Josh':"); jdbcTemplate.query( "SELECT id, first_name, last_name FROM customers WHERE first_name = ?", new Object[]{"Josh"}, (rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"))) .forEach(customer -> log.info(customer.toString()));
下面在mysql的客户端进行了验证:
mysql> select * from customers; +----+------------+-----------+ | id | first_name | last_name | +----+------------+-----------+ | 1 | John | Woo | | 2 | Jeff | Dean | | 3 | Josh | Bloch | | 4 | Josh | Long | +----+------------+-----------+ 4 rows in set (0.00 sec)
5. 遇到的一些坑
maven配置
使用了jdk8的lamda表达式,必须在maven中配置java.version
<properties> <java.version>1.8</java.version> </properties>
docker服务重启
docker这个服务挂了,容器也就跟着挂了,并没有重启,应该在运行容器的时候带上--restart=always这个参数
更多Mysql内容来自木庄网络博客
标签:Mysql
相关阅读 >>
更多相关阅读请进入《mysql》频道 >>
数据库系统概念 第6版
本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。