介绍三种操作数据库的对比
第一种直接JDBC
-
思路:写个工具类,获取连接的方法,释放资源的方法
-
实现:
pom.xml添加mysql驱动包<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency>
写工具类utils.java
public class JdbcUtils { public static Connection getConn() throws Exception{} public static void release(ResultSet rs, Statement sm, Connection conn){} }
写单元测试test.java
public class JDBCUtilsTest { @Test public void testGetConn() throws Exception { Connection connection = JDBCUtils.getConnection(); Assert.assertNotNull(connection); } }
写业务代码
先实体entity/Student.java
public class Student {
private int id;
private String name;
private int age;
get()/set()...
}
在数据接口层dao/StudentDao.java
public interface StudentDao {
public List<Student> queryAllStudent();
public void saveStudent(Student student);
}
在数据实现层dao/StudentDaoImpl.java
public class StudentDaoImpl implements StudentDao{
@Override
public List<Student> queryAllStudent() {
List<Student> list = new ArrayList<>();
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = JDBCUtils.getConnection();
String sql = "select * from student";
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
while (resultSet.next()) {
Student student = new Student();
student.setId(resultSet.getInt("id"));
student.setName(resultSet.getString("name"));
student.setAge(resultSet.getInt("age"));
list.add(student);
}
}catch (Exception e){
e.printStackTrace();
}finally {
JDBCUtils.release(resultSet,statement,connection);
}
return list;
}
@Override
public void saveStudent(Student student) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = JDBCUtils.getConnection();
String sql = "insert into student (name,age) values (?,?)";
statement = connection.prepareStatement(sql);
statement.setString(1,student.getName());
statement.setInt(2,student.getAge());
statement.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}finally {
JDBCUtils.release(resultSet,statement,connection);
}
}
}
第二种就是spring Template
-
痛点:在第一种写业务代码时,与数据库交互都需要处理
Connection,Statement,ResultSet对象,很繁琐 -
思路:通过操作模板就能执行sql语句操作数据库
通过bean来维护所有人,datasource,template,dao层
在bean里面把datasource引入template,在数据实现层引入template,在实现层的代码中get/set注入属性,通过属性操作db
这种思路的好处,重复代码只需要通过bean管理dao,在dao注入属性,即可操作数据库 -
实现:
pom.xml添加jar包<dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.5.RELEASE</version> </dependency>
写resources/beans.xml配置
<!--datasource-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/zxkdb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
写单元测试test.java
public class DataSourceTest {
private ApplicationContext context = null;
@Before
public void createContext(){
context = new ClassPathXmlApplicationContext("beans.xml");
}
@After
public void distoryContext(){
context = null;
}
@Test
public void testDataSource(){
DataSource dataSource = (DataSource) context.getBean("dataSource");
Assert.assertNotNull(dataSource);
}
写业务代码
先实体entity/Student.java
public class Student {
private int id;
private String name;
private int age;
get()/set()...
}
在数据接口层dao/StudentDao.java
public interface StudentDao {
public List<Student> queryAllStudent();
public void saveStudent(Student student);
}
在数据实现层dao/StudentDaoImpl.java
public class SpringJdbcImpl implements StudentDao {
//在数据实现层代码中set/get注入模板属性
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public List<Student> queryAllStudent() {
final List<Student> list = new ArrayList<>();
String sql = "select * from student";
jdbcTemplate.query(sql,new RowCallbackHandler(){
@Override
public void processRow(ResultSet rs) throws SQLException {
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
list.add(student);
}
});
return list;
}
@Override
public void saveStudent(Student student) {
String sql = "insert into student (name,age) values (?,?)";
jdbcTemplate.update(sql,new Object[]{student.getName(),student.getAge()});
}
}
在beans.xml注入实体
<!--模板引用数据源-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--实体类引用模板-->
<bean id="studentDao" class="com.imooc.dao.SpringJdbcImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
第三种就是spring data
-
痛点:数据实现层的代码虽然少了,但注入模板也存在重复,分页等通用功能还需要开发,等等
-
思路:前面两种方式,都需要自己在数据库中手动建表,springdata可以实现实体与表映射,直接写实体类即可,映射通过@注解实现
只需要写接口,写方法,不需要写实现类 -
实现:
pom.xml添加mysql驱动包<!--spring data jpa--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.8.0.RELEASE</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.6.Final</version> </dependency>
写resources/beans-new.xml配置
<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.imooc"/>
<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>
写单元测试test.java
public class SpringDataTest {
private ApplicationContext context = null;
@Before
public void createContext(){
context = new ClassPathXmlApplicationContext("beans-new.xml");
}
@After
public void distoryContext(){
context = null;
}
@Test
public void testCreateTab(){
// 自动创建表
}
}
写业务代码
之前的事务是靠代码维护的,现在要交给框架维护,我们需要配置
网友评论