准备好maven包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.14</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<!--mysql driver-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!--jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
druid.properties配置文件
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/demo
username=root
password=543241338
initialSize=5
maxActive=10
maxWait=3000
使用druid连接池
InputStream resourceAsStream = MyClass.class.getClassLoader().getResourceAsStream("conf/druid.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);
使用JdbcTemplate
//使用druid源
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
//查询数据库自动转换到实体模型
List<UserModel> rowMapper = jdbcTemplate.query("SELECT name,age FROM users", new BeanPropertyRowMapper<>(UserModel.class));
System.out.println(rowMapper.get(0).getName());
实体模型
public class UserModel {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
网友评论