Spring第五篇 jdbcTemplate
jdbc 是什么
jdbc 是 Java 的数据库连接框架,通过 jdbc 提供的抽象,jdbc 通过接口的方式,规范了各个数据库的行为,各个数据库 dbms 写对应的数据库驱动,来对接 jdbc,从而 jdbc 拥有操作各个数据库的能力
jdbcTemplate 是什么
jdbcTemplate 是 spring 推出的 jdbc 框架,通过依赖注入的方式,完成数据库连接的管理
jdbcTemplate 依赖导入
修改 pom.xml 文件
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.10</version>
</dependency>
加入这两个依赖,并使用 maven 重新拉取依赖
数据库数据源配置
xml 方式
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="url" value="jdbc:mysql://localhost:3306/hello"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
</bean>
<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="dataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
通过 DataSourceTransactionManager 类提供数据源管理,可以使用 druid 数据源,在 druid 类中,注入,数据库的相关信息,最后,在 JdbcTemplate 这个类里注入 dataSource 信息
在数据库操作的 Dao 类里注入 jdbcTemplate
public class UserDaoImlp implements UserDao{
@Autowired
public JdbcTemplate jdbcTemplate;
}
JdbcTemplate 增删改查
插入数据
单条插入
public void Inset(){
String sql="INSERT INTO userinfo(`account`,`password`,`usertype`)VALUES(?,?,?)";
jdbcTemplate.update(sql,args);
}
批量插入
调用 JdbcTemplate 的 batchupdate 方法
修改
同上
查询
查询一个字段
public int SelcetConnt(){
String sql="SELECT COUNT(*) FROM userinfo";
int count= jdbcTemplate.queryForObject(sql,int.class);
return count;
}
查询多字段,组合成对象
- 设计实体对象
public class User {
private String account;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsertype() {
return usertype;
}
public void setUsertype(String usertype) {
this.usertype = usertype;
}
private String password;
private String usertype;
public String toString(){
return this.getAccount()+" "+this.getPassword()+" "+this.getUsertype();
}
}
- 查询
public entity.User SelectObject(){
String sql="SELECT `account`,`password`,`usertype` FROM userinfo WHERE account='test'";
User user=jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class));
return user;
}
查询多条多字段
public List<User> SelectList(){
String sql="SELECT `account`,`password`,`usertype` FROM userinfo ";
List<User> user= jdbcTemplate.query(sql,new BeanPropertyRowMapper<User>(User.class));
return user;
}
删除
同添加,修改
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 小周の代码之路!
评论