springdata

2019-10-03  本文已影响0人  ___Hello

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

第一种直接JDBC

写业务代码
先实体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

写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

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

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

上一篇下一篇

猜你喜欢

热点阅读