springdata

介绍三种操作数据库的对比

第一种直接JDBC

  • 思路:写个工具类,获取连接的方法,释放资源的方法

  • 实现:
    pom.xml添加mysql驱动包

      
          mysql
          mysql-connector-java
          5.1.38
      
      
          junit
          junit
           4.10
      
    

    写工具类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 queryAllStudent();
    public void saveStudent(Student student);
}

在数据实现层dao/StudentDaoImpl.java

  public class StudentDaoImpl implements StudentDao{
    @Override
    public List queryAllStudent() {
        List 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包

    
        org.springframework
        spring-jdbc
        4.3.5.RELEASE
    
    
        org.springframework
        spring-context
        4.3.5.RELEASE
    
    

写resources/beans.xml配置

    
    
            
            
            
            
    

写单元测试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 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 queryAllStudent() {
          final  List 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注入实体

    
    
            
    
    
    
            
    

第三种就是spring data

  • 痛点:数据实现层的代码虽然少了,但注入模板也存在重复,分页等通用功能还需要开发,等等

  • 思路:前面两种方式,都需要自己在数据库中手动建表,springdata可以实现实体与表映射,直接写实体类即可,映射通过@注解实现
    只需要写接口,写方法,不需要写实现类

  • 实现:
    pom.xml添加mysql驱动包

    
    
        org.springframework.data
        spring-data-jpa
        1.8.0.RELEASE
    
    
      org.hibernate
      hibernate-entitymanager
      4.3.6.Final
    
    

写resources/beans-new.xml配置

  
            
            
                    
            
            

            
                    
                            org.hibernate.cfg.ImprovedNamingStrategy
                            org.hibernate.dialect.MySQL5InnoDBDialect
                            true
                            true
                            update
                    
            

    

写单元测试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(){
      // 自动创建表
  }
}

写业务代码
之前的事务是靠代码维护的,现在要交给框架维护,我们需要配置

你可能感兴趣的:(springdata)