spring5入门(十四):JdbcTemplate使用,添加数据
- JdbcTemplate简介
Spring 框架对 JDBC 进行封装,使用 JdbcTemplate 方便实现对数据库操作
-
导入所需依赖
-
新建表
-
代码实现
# 实体类
public class Book {
private Integer id;
private String name;
private String price;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
# 持久层接口
public interface BookDao {
void addBook(Book book);
}
# 持久层实现
@Repository
public class BookDaoImpl implements BookDao {
//注入 JdbcTemplate
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void addBook(Book book) {
//1 创建 sql 语句
String sql = "insert into book values(?,?,?)";
//2 调用方法实现
Object[] args = {book.getId(), book.getName(), book.getPrice()};
int update = jdbcTemplate.update(sql,args);
System.out.println(update);
}
}
# 业务层
@Service
public class BookService {
//注入 dao
@Autowired
private BookDao bookDao;
public void addBook(Book book){
bookDao.addBook(book);
}
}
# 测试方法
public class Test1 {
@Test
public void testAdd() {
ApplicationContext context =
new ClassPathXmlApplicationContext("bean1.xml");
BookService bookService = context.getBean("bookService", BookService.class);
Book book = new Book();
book.setId(1);
book.setName("java");
book.setPrice("12");
bookService.addBook(book);
}
}
# bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 组件扫描 -->
<context:component-scan base-package="com.ychen"></context:component-scan>
<!-- 数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url" value="jdbc:mysql://127.0.0.1:3306/jdbc" />
<property name="username" value="root" />
<property name="password" value="123456" />
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
</bean>
<!-- JdbcTemplate对象 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
# 控制台
4月 19, 2022 10:11:26 下午 com.alibaba.druid.support.logging.JakartaCommonsLoggingImpl info
信息: {dataSource-1} inited
1
Process finished with exit code 0
- 查看数据库,是否添加成功