每次开发基本上都是使用mybatis,对于hibernate,估计也忘了差不多。今天来重温了一下hibernate的配置实现。
第一步,肯定是配置文件:
/** * Created by alan on 2018/6/18. */ @Configuration public class HibernateConfig { private String driver = "com.mysql.jdbc.Driver"; private String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8"; private String username = "root"; private String password = "root"; public HibernateConfig(){ } @Bean public BasicDataSource dataSource(){ BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setInitialSize(5); dataSource.setMaxIdle(100); dataSource.setMaxOpenPreparedStatements(100); dataSource.setCacheState(true); dataSource.setMaxTotal(1000); dataSource.setTestWhileIdle(true); dataSource.setValidationQuery("SELECT 1"); dataSource.setTimeBetweenEvictionRunsMillis(3600000L); dataSource.setMinEvictableIdleTimeMillis(1800000L); dataSource.setTestOnBorrow(true); return dataSource; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(){ HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); adapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect"); Properties properties = new Properties(); properties.setProperty("hibernate.dialect","org.hibernate.dialect.MySQL5InnoDBDialect"); properties.setProperty("hibernate.show_sql","true"); properties.setProperty("hibernate.format_sql","true"); properties.setProperty("hibernate.auto","update"); LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean(); factoryBean.setPersistenceUnitName("SpringJPA"); factoryBean.setJpaVendorAdapter(adapter); factoryBean.setDataSource(this.dataSource()); factoryBean.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE); factoryBean.setValidationMode(ValidationMode.NONE); /** * scan @Entity */ factoryBean.setPackagesToScan("com.example.demo.model","com.example.demo.repository"); //factoryBean.setMappingResources("com/example/demo/repository/resource/User.hbm.xml"); factoryBean.setJpaProperties(properties); return factoryBean; } @Bean public PlatformTransactionManager platformTransactionManager(){ return new JpaTransactionManager(this.entityManagerFactory().getObject()); } @Bean public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor(){ return new PersistenceAnnotationBeanPostProcessor(); } }
配置文件由dateSource、LocalContainerEntityManagerFactoryBean、PlatformTransactionManager组成,改有的都有了,现在来实现DAO层,emmmmm,本人比较懒,直接在service层里直接写代码了,如下:
public class TestByHibernateServiceImpl { private static final Logger logger = LoggerFactory.getLogger(TestByHibernateServiceImpl.class); @PersistenceContext private EntityManager manager; @Resource private LxUserMapper userMapper; public TestByHibernateServiceImpl() { } public List<LxUserModel> getAll() { Query query = manager.createNativeQuery("SELECT * FROM lx_user ORDER BY id DESC",LxUserModel.class); return query.getResultList(); } public LxUserModel getRow() { // return manager.createQuery("SELECT a FROM LxUserModel a ORDER BY id DESC",LxUserModel.class).setMaxResults(1).getSingleResult(); return userMapper.getRow(); } public int add(LxUserModel userModel) { manager.persist(userModel); return userModel.getId(); }
哇塞,跟昨天写的那篇文章比,正篇肯真简短,没错大部分代码都是EntityManager去实现了,很多人包括我都因为懒,不去写自己的DAO实现,而去用开源的,如果有时间还是建议自己实现或看一下EntityManager的原理。
/** * Created by alan on 2018/6/18. */ @Repository public interface LxUserMapper extends JpaRepository<LxUserModel,Integer> { @Query(value = "SELECT * FROM lx_user ORDER BY id DESC limit 1",nativeQuery = true) LxUserModel getRow(); }
下面提供一个例子,在真实场景中,查询数据可是千奇百怪,所以按照自己的思维封装了几个通用的方法,当然啦,肯定是使用了EntityManager:
/** * Created by alan.luo on 2017/10/22. */ public abstract class AbstractDefaultRepository<E extends Serializable> extends AbstractDefaultBaseRepository<E> { @PersistenceContext private EntityManager manager; /** * get all the data. * @param page * @param where * @param order * @param isDesc * @return */ @Override public List<E> getAll(int page, List<PredicatePojo> where, String order, boolean isDesc) { CriteriaBuilder builder = this.manager.getCriteriaBuilder(); CriteriaQuery<E> query = builder.createQuery(this.entityClass); Root<E> root = query.from(this.entityClass); CriteriaQuery<E> select = query.select(root); if (order != null && !"".equals(order)){ if (isDesc){ select.orderBy(builder.desc(root.get(order))); }else { select.orderBy(builder.asc(root.get(order))); } } select.where(getListPredicate(where,builder,root)); TypedQuery<E> typedQuery = this.manager.createQuery(select); typedQuery.setFirstResult((page - 1) * ConstantInit.PAGE_SIZE); typedQuery.setMaxResults(ConstantInit.PAGE_SIZE); return typedQuery.getResultList(); } /** * search all the data. * @param page * @param condition * @param order * @param isDesc * @return */ @Override public PagePojo<E> search(int page, List<PredicatePojo> condition, String order, boolean isDesc){ CriteriaBuilder builder = this.manager.getCriteriaBuilder(); CriteriaQuery<Long> query = builder.createQuery(Long.class); Root<E> root = query.from(this.entityClass); CriteriaQuery<Long> select = query.select(builder.count(root)); select.where(getListPredicate(condition,builder,root)); long total = this.manager.createQuery(select).getSingleResult(); PagePojo<E> pages = new PagePojo<E>((long) page,total); pages.setList(this.getAll(page,condition,order,isDesc)); return pages; } @Override public E getRowById(int id) { return this.manager.find(this.entityClass,id); } @Override public void add(E o) { this.manager.persist(o); } @Override public void update(E o) { this.manager.merge(o); } @Override public void remove(E o) { this.manager.remove(o); } @Override public int removeById(int id) { CriteriaBuilder builder = this.manager.getCriteriaBuilder(); CriteriaDelete<E> q = builder.createCriteriaDelete(this.entityClass); return this.manager .createQuery(q.where(builder.equal(q.from(this.entityClass).get("id"),id))) .executeUpdate(); } /** * * List<PredicatePojo> where = new ArrayList<>(); * where.add(new PredicatePojo("id","81", Criteria.lt)); * where.add(new PredicatePojo("age","10", Criteria.gt)); * * List<PredicatePojo> where = new ArrayList<>(); * if (userName != null){ * userName = "%" + userName + "%"; * List<PredicatePojo> like = new ArrayList<>(); * like.add(new PredicatePojo("username",userName, Criteria.like)); * like.add(new PredicatePojo("mobile",userName, Criteria.like)); * like.add(new PredicatePojo("email",userName, Criteria.like)); * * PredicatePojo pojo = new PredicatePojo(); * pojo.setLikeObj(like); * pojo.setCriteria(Criteria.like); * where.add(pojo); * } * * * * parser predicate. * @param where * @param builder * @param root * @return */ protected Predicate[] getListPredicate(List<PredicatePojo> where,CriteriaBuilder builder,Root<E> root){ Predicate[] predicates = new Predicate[where.size()]; Predicate[] like; if (where != null && where.size() > 0){ Predicate p = null; for (int i = 0; i < where.size();i++){ Criteria ca = where.get(i).getCriteria(); switch (ca){ case equal: p = builder.equal(root.get(where.get(i).getKey()),where.get(i).getValue()); break; case notEqual: p = builder.notEqual(root.get(where.get(i).getKey()),where.get(i).getValue()); break; case isNull: p = builder.isNull(root.get(where.get(i).getKey())); break; case isNotNull: p = builder.isNotNull(root.get(where.get(i).getKey())); break; case gt: p = builder.gt(root.get(where.get(i).getKey()),Double.valueOf(where.get(i).getValue())); break; case lt: p = builder.lt(root.get(where.get(i).getKey()),Double.valueOf(where.get(i).getValue())); break; case ge: p = builder.ge(root.get(where.get(i).getKey()),Double.valueOf(where.get(i).getValue())); break; case le: p = builder.le(root.get(where.get(i).getKey()),Double.valueOf(where.get(i).getValue())); break; case isFalse: p = builder.isFalse(root.get(where.get(i).getKey())); break; case isTrue: p = builder.isTrue(root.get(where.get(i).getKey())); break; case not: p = builder.not(root.get(where.get(i).getKey())); break; case like: like = new Predicate[where.get(i).getLikeObj().size()]; for (int j = 0; j < where.get(i).getLikeObj().size();j++){ like[j] = builder.like(root.get(where.get(i).getLikeObj().get(j).getKey()) ,where.get(i).getLikeObj().get(j).getValue()); } p = builder.or(like); break; case notLike: like = new Predicate[where.get(i).getLikeObj().size()]; for (int j = 0; j < where.get(i).getLikeObj().size();j++){ like[j] = builder.notLike(root.get(where.get(i).getLikeObj().get(j).getKey()) ,where.get(i).getLikeObj().get(j).getValue()); } p = builder.and(like); break; } predicates[i] = p; } } return predicates; } }
近期评论