美文网首页
Spring学习(十一)使用对象-关系映射持久化数据

Spring学习(十一)使用对象-关系映射持久化数据

作者: 木书 | 来源:发表于2017-11-28 16:46 被阅读19次

    一、spring集成hibernate

    • 配置Session·Factory
    @Bean
      public SessionFactory sessionFactoryBean() {
        try {
          LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
          lsfb.setDataSource(dataSource());
          lsfb.setPackagesToScan("spittr.domain");
          Properties props = new Properties();
          //props.setProperty("dialect", "org.hibernate.dialect.H2Dialect");
          props.setProperty("dialect", "org.hibernate.dialect.MySQL5Dialect");
          lsfb.setHibernateProperties(props);
          lsfb.afterPropertiesSet();
          SessionFactory object = lsfb.getObject();
          return object;
        } catch (IOException e) {
          return null;
        }
    
    • 创建Repository
    @Repository
    public class HibernateSpitterRepository implements SpitterRepository {
    
        private SessionFactory sessionFactory;
    
        @Inject
        public HibernateSpitterRepository(SessionFactory sessionFactory) {
            this.sessionFactory = sessionFactory;        //<co id="co_InjectSessionFactory"/>
        }
        
        private Session currentSession() {
            return sessionFactory.getCurrentSession();//<co id="co_RetrieveCurrentSession"/>
        }
        
        public long count() {
            return findAll().size();
        }
    
        public Spitter save(Spitter spitter) {
            Serializable id = currentSession().save(spitter);  //<co id="co_UseCurrentSession"/>
            return new Spitter((Long) id, 
                    spitter.getUsername(), 
                    spitter.getPassword(), 
                    spitter.getFullName(), 
                    spitter.getEmail(), 
                    spitter.isUpdateByEmail());
        }
    
        public Spitter findOne(long id) {
            return (Spitter) currentSession().get(Spitter.class, id); 
        }
    
        public Spitter findByUsername(String username) {        
            return (Spitter) currentSession() 
                    .createCriteria(Spitter.class) 
                    .add(Restrictions.eq("username", username))
                    .list().get(0);
        }
    
        public List<Spitter> findAll() {
            return (List<Spitter>) currentSession() 
                    .createCriteria(Spitter.class).list(); 
        }
        
    }
    

    二、Spring使用jpa

    • 配置容器管理类型的JPA
    //声明LocalContainerEntity-ManagerFactoryBean
    @Bean
      public LocalContainerEntityManagerFactoryBean emf(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource);
        emf.setPersistenceUnitName("spittr");
        emf.setJpaVendorAdapter(jpaVendorAdapter);
        emf.setPackagesToScan("spittr.domain");
        return emf;
      }
    //配置JpaVendorAdapter 
     @Bean
      public JpaVendorAdapter jpaVendorAdapter() {
        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setDatabase(Database.H2);
        adapter.setShowSql(true);
        adapter.setGenerateDdl(false);
        adapter.setDatabasePlatform("org.hibernate.dialect.H2Dialect");
        return adapter;
      }
    
    • 编写Repository
    @Repository
    public class JpaSpitterRepository implements SpitterRepository {
    
        @PersistenceContext
        private EntityManager entityManager;
    
        public long count() {
            return findAll().size();
        }
    
        public Spitter save(Spitter spitter) {
            entityManager.persist(spitter);
            return spitter;
        }
    
        public Spitter findOne(long id) {
            return entityManager.find(Spitter.class, id);
        }
    
        public Spitter findByUsername(String username) {        
            return (Spitter) entityManager.createQuery("select s from Spitter s where s.username=?").setParameter(1, username).getSingleResult();
        }
    
        public List<Spitter> findAll() {
            return (List<Spitter>) entityManager.createQuery("select s from Spitter s").getResultList();
        }
        
    }
    

    三、编写最终版Spring Data JPA Repository

    public interface SpitterSweeper {
    
        int eliteSweep();
    
    }
    
    public interface SpitterRepository extends JpaRepository<Spitter, Long>, SpitterSweeper {
          
        Spitter findByUsername(String username);
        
        List<Spitter> findByUsernameOrFullNameLike(String username, String fullName);
    
    }
    
    public class SpitterRepositoryImpl implements SpitterSweeper {
    
        @PersistenceContext
        private EntityManager em;
        
        public int eliteSweep() {
          String update = 
              "UPDATE Spitter spitter " +
                "SET spitter.status = 'Elite' " +
                "WHERE spitter.status = 'Newbie' " +
                "AND spitter.id IN (" +
                "SELECT s FROM Spitter s WHERE (" +
                "  SELECT COUNT(spittles) FROM s.spittles spittles) > 10000" +
                ")";
            return em.createQuery(update).executeUpdate();
          }
          public List<Spitter> eliteSweep2() {
            System.out.println("SpitterRepositoryImpl.eliteSweep2()");
            String sec = "select s from Spitter s ";
            List<Spitter> list = em.createQuery(sec).getResultList();
            return list;
        }   
    }
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes=JpaConfig.class)
    public class SpitterRepositoryTest {
            //测试代码
            @Test
            @Transactional
            public void testA() {
              List<Spitter> list = spitterRepository.eliteSweep2();
              for(Spitter spitter : list)
                 System.out.println("username:"+spitter.getUsername());
        }
    }

    相关文章

      网友评论

          本文标题:Spring学习(十一)使用对象-关系映射持久化数据

          本文链接:https://www.haomeiwen.com/subject/frosbxtx.html