2、Spring JdbcTemplate
(1)添加依赖
<!-- spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.1</version> </dependency>
(2)配置beans.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/data"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> <bean id="studentDao" class="com.mouday.dao.impl.StudentDaoSpringJdbcImpl"> <property name="jdbcTemplate" ref="jdbcTemplate"/> </bean> </beans>
(3)Dao实现类
package com.mouday.dao.impl; import com.mouday.dao.StudentDao; import com.mouday.domain.Student; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * 学生访问接口实现类 */ public class StudentDaoSpringJdbcImpl implements StudentDao { private JdbcTemplate jdbcTemplate; public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public List<Student> query() { List<Student> students = new ArrayList<>(); String sql = "select id, name, age from student"; jdbcTemplate.query(sql, new RowCallbackHandler() { @Override public void processRow(ResultSet resultSet) throws SQLException { Integer id = resultSet.getInt("id"); String name = resultSet.getString("name"); Integer age = resultSet.getInt("age"); Student student = new Student(); student.setId(id); student.setName(name); student.setAge(age); students.add(student); } }); return students; } @Override public Integer insert(Student student) { String sql = "insert into student (name, age) values (?, ?)"; KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, student.getName()); ps.setInt(2, student.getAge()); return ps; } }, keyHolder); return keyHolder.getKey().intValue(); } }
测试类
package com.mouday; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; public class DataSourceTest { ApplicationContext context = null; @Before public void setup() { System.out.println("StudentDaoSpringJdbcImplTest.setup"); context = new ClassPathXmlApplicationContext("beans.xml"); } @After public void tearDown() { System.out.println("StudentDaoSpringJdbcImplTest.tearDown"); context = null; } @Test public void testDataSource() { DataSource dataSource = context.getBean("dataSource", DataSource.class); System.out.println(dataSource); Assert.assertNotNull(dataSource); } @Test public void testJdbcTemplate() { JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate", JdbcTemplate.class); System.out.println(jdbcTemplate); Assert.assertNotNull(jdbcTemplate); } } package com.mouday.dao.impl; import com.mouday.dao.StudentDao; import com.mouday.domain.Student; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; public class StudentDaoSpringJdbcImplTest { ApplicationContext context = null; StudentDao studentDao = null; @Before public void setup() { System.out.println("StudentDaoSpringJdbcImplTest.setup"); context = new ClassPathXmlApplicationContext("beans.xml"); studentDao = context.getBean("studentDao", StudentDao.class); } @After public void tearDown() { System.out.println("StudentDaoSpringJdbcImplTest.tearDown"); context = null; studentDao = null; } @Test public void testQuery() { List<Student> students = studentDao.query(); System.out.println(students); } @Test public void testInsert() { Student student = new Student(); student.setName("曹操"); student.setAge(50); Integer id = studentDao.insert(student); System.out.println(id); } }
3、优缺点分析
弊端:
Dao有大量代码
DaoImpl有重复代码
三、SpringData 快速开始
1、开发环境搭建
依赖
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>5.4.24.Final</version> </dependency>
配置beans-jpa.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:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!--1 配置数据源--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/data"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <!--2 配置EntityManagerFactory--> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/> </property> <property name="packagesToScan" value="com.mouday"/> <property name="jpaProperties"> <props> <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <!--3 配置事务管理器--> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <!--4 配置支持注解的事务--> <tx:annotation-driven transaction-manager="transactionManager"/> <!--5 配置spring data--> <jpa:repositories base-package="com.mouday" entity-manager-factory-ref="entityManagerFactory"/> <context:component-scan base-package="com.mouday"/> </beans>
定义实体
package com.mouday.domain; import javax.persistence.*; /** * 雇员表 先开发实体->自动生成数据表 */ @Entity public class Employee { private Integer id; private String name; private Integer age; // 主键自增 @GeneratedValue(strategy= GenerationType.IDENTITY) @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(length = 20) 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; } @Override public String toString() { return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } } ;
自动建表测试
package com.mouday; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; public class SpringDataJpaTest { ApplicationContext context = null; @Before public void setup() { System.out.println("StudentDaoSpringJdbcImplTest.setup"); context = new ClassPathXmlApplicationContext("beans-jpa.xml"); } @After public void tearDown() { System.out.println("StudentDaoSpringJdbcImplTest.tearDown"); context = null; } @Test public void testEntityManagerFactory() { } }
2、Spring Data JPA 开发
定义接口
package com.mouday.repository;
import com.mouday.domain.Employee;
import org.springframework.data.repository.Repository;
public interface EmployeeRepository extends Repository<Employee, Integer> {
public Employee findByName(String name);
}
插入数据
package com.mouday.repository; import com.mouday.domain.Employee; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class EmployeeRepositoryTest { ApplicationContext context = null; EmployeeRepository repository = null; @Before public void setup() { System.out.println("StudentDaoSpringJdbcImplTest.setup"); context = new ClassPathXmlApplicationContext("beans-jpa.xml"); repository = context.getBean(EmployeeRepository.class); } @After public void tearDown() { System.out.println("StudentDaoSpringJdbcImplTest.tearDown"); context = null; } @Test public void testFindByName() { Employee employee = repository.findByName("刘备"); System.out.println(employee); } }
SpringDATA:
Repository核心
Repository Definition 定义
Repository Query Specifications 查询规则 规范 技术参数
Query Annotation 查询注解
Update/Delete/Transaction 对事务的细粒度优秀支持