文章目录
Spring数据库开发
Spring Jdbc Template
Spring JDBC配置
-
Spring JDBC模块主要由四个包组成
-
配置ApplicationContext文件
<!--注入数据源-->
<bean id="dataSource" class="com.springframework.jdbc.datesource.DriverManagerDateSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="Url" value="jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&serverTimezone=GMT&useUnicode=true&characterEncoding=UTF-8"/>
<property name="user"value="用户名"/>
<property name="password" value="密码}"/>
<bean/>
<!--配置Jdbc模板-->
<bean id="jdbcTemplate" class="org.springframwork.jdbc.core.JdbcTemplate">
<property name="dtaeSource" ref="dateSouce"/>
<bean/>
<!-- 配置需要的实例化bean-->
<bean id="xxx" class="xxx">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
<bean/>
<beans/>
Jdbc Template类的常用方法
Jdbc Template类的execute()方法
- 使用esecute()方法建表
public class Test {
public static void main(String[] args) {
//加载配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
//获取JdbcTemplate实例
JdbcTemplate jdbcTemplate = (JdbcTemplate)applicationContext.getBean("jdbcTemplate");
//使用execute()方法执行SQL语句,创建用户账户管理表account
jdbcTemplate.execute("creat table account("+
"id int primary key auto_increment,"+
"username varchar(50),"+
"balance double)");
}
}
Jdbc Template类的update()方法
- update()方法的常用方法
update()使用事例
- 创建实体类
public class Account {
private Integer id;
private String username;
private Double balance;
@Override
public String toString() {
return "Account{" +
"id=" + id +
", username='" + username + '\'' +
", balance=" + balance +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
}
}
- 创建Dao层接口方法
public interface AccuntDao {
//添加
public int addAccount(Account account);
}
- 实现方法
public class Test implements AccuntDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
//添加
public int addAccount(Account account){
String sql = "insert into account(username,balance) value(?,?)";
Object[] obj = new Object[]{ account.getUsername(),account.getBalance()};
int num = this.jdbcTemplate.update(sql,obj);
return num;
}
Jdbc Template类的query()方法
- 常用的query()方法
qure()方法使用事例
- 创建Dao层接口方法、
public interface AccuntDao {
//通过id进行查询
publi Account findAccountById(int id);
}
- 实现方法
//通过id进行查询
public Account findAccountById(int id){
//定义sql
String sql = "select * from account where id=?";
//创建一个新的BeanProertyRowMapper对象
RowMapper<Account> rowMapper = new BeanProertyRowMapper<Account>(Account.class);
//将id绑定到sql语句中,通过RowMapper返回一个Object类型的单行记录
return this.jdbcTemplate.queryForObject(sql,rowMapper,id) ;
}