实例对比 hibernate, spring data jpa, mybatis 选型参考
spring data jpa-由mybatis切换
首先看hibernate:
-
public interface UserDao{
-
List<User> findByNameLikeAndAgeGreaterThan(String firstName,Integer age);
-
}
-
public class UserDaoImpl implements UserDao{
-
@Override
-
public List<User> findByFirstNameAndAge(String firstName, Integer age) {
-
//具体hql查找:"from User where name like '%'"+firstName + "and age > " + age;
-
return hibernateTemplateMysql.execute(new HibernateCallback() {
-
@Override
-
public Object doInHibernate(Session session) throws HibernateException {
-
String hql = "from User where name like '?' and age > ?";
-
Query query = session.createQuery(hql);
-
query.setParameter(0, firstName+"");
-
query.setParameter(1, age);
-
return query.uniqueResult();
-
}
-
});
-
}
-
}
-
@Mapper
-
public interface UserMapper {
-
Increment findByNameLikeAndAgeGreaterThan(String name,int age);
-
}
-
<select id="findByNameLikeAndAgeGreaterThan" parameterType="java.lang.Integer" resultMap="UserMap">
-
select
-
u.*
-
from
-
user u
-
<where>
-
u.name like ?1 and u.age>?2
-
</where>
-
</select>
-
<resultMap id="UserMap" type="com.txxs.po.User">
-
<result column="id" property="id"/>
-
<result column="name" property="name"/>
-
<result column="age" property="age"/>
-
</resultMap>
-
public interface UserDao extends JpaRepository<User, Serializable>{
-
List<User> findByNameLikeAndAgeGreaterThan(String name,Integer age);
-
}
-
//为了增加代码的可读性可以使用注解的方式,这样方法的命名就不需要严格按照规范
-
@Query("select * from User u where u.name like ?1 and u.age>?2")
Keyword | Sample | JPQL snippet |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-
@Repository
-
public class CommonRepository<T> {
-
@PersistenceContext
-
protected EntityManager entityManager;
-
/**
-
* 添加和批量添加数据
-
* @param lists
-
*/
-
@Transactional
-
public void batchAddCommon(List<T> lists){
-
int size = lists.size();
-
for (int i = 0; i < size; i++) {
-
entityManager.persist(lists.get(i));
-
if (i % 100 == 0 || i == (size - 1)) {
-
entityManager.flush();
-
entityManager.clear();
-
}
-
}
-
}
-
/**
-
* 数据的批量更新
-
* @param lists
-
*/
-
@Transactional
-
public void batchUpdate(List<T> lists) {
-
int size = lists.size();
-
for (int i = 0; i < size; i++) {
-
entityManager.merge(lists.get(i));
-
if (i % 100 == 0 || i == (size - 1)) {
-
entityManager.flush();
-
entityManager.clear();
-
}
-
}
-
}
-
}
-
//修改方法和删除方法都需要添加@Modifying,占位符是从1开始而不是开始的
-
@Modifying
-
@Query("update table n set n.column1 =?1 where n.column2 = ?2")
-
Integer updateObject(String one,String two);
-
@Modifying
-
@Query("delete from table n where n.column1 = ?1")
-
Integer getObject(String one);
-
//查询某一个字段的时候需要制定相应的类型,select全量数据的使用直接使用别名n即可,原生的SQL需要使用n.*
-
@Query("select n.column1 as String from table n where n.column2 is null or n.column2 =''")
-
List<String> getObject();
-
//原生SQL,进行了连表操作,并且查询了满足数组条件
-
@Query(value="select s.*, i.* from table1 s, table2 i where i.column1 = s.column1 and i.column1 in (?1) order by s.id desc", nativeQuery = true)
-
List<Server> getObject(List<Integer> arry);
-
<select id="queryNotUsedObject" parameterType="com.txxs.po.Object" resultType="java.lang.Integer" >
-
select
-
DISTINCT (i.column1),
-
SUM(CASE WHEN i.column7=#{column7} THEN 1 ELSE 0 END) used,
-
sum(CASE WHEN i.column7 IS NULL THEN 1 ELSE 0 END) not_used
-
from
-
table1 i,
-
table2 s
-
<where>
-
<if test="column2 != null and column2 != '' ">
-
and s.column2 = #{column2}
-
</if>
-
<if test="column3 != null and column3 != '' ">
-
and s.column3 = #{column3}
-
</if>
-
<if test="column4 != null and column4 != '' ">
-
and i.column4 like '${column4}%'
-
</if>
-
<if test="column5 != null and column5 != '' ">
-
and i.column5 like '${column5}%'
-
</if>
-
<if test="column6 != null and column6 != '' ">
-
and i.column6 like '${column6}%'
-
</if>
-
and s.column1 = i.column1
-
</where>
-
GROUP BY column1
-
having used =0 and not_used>0
-
ORDER BY s.id DESC
-
<if test="page != null and page>=0" >
-
limit #{page} , #{size}
-
</if>
-
</select>
-
public Page<Object> queryNotUsedObject(final Object query){
-
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
-
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();
-
//查询的根
-
Root<Server> root = criteriaQuery.from(entityManager.getMetamodel().entity(Object.class));
-
//判断参数
-
List<Predicate> predicates = new ArrayList<Predicate>();
-
if(null != query.getColumn1()){
-
predicates.add(criteriaBuilder.equal(root.get("Column1"), query.getColumn1()));
-
}
-
if(null != query.getColumn2()){
-
predicates.add(criteriaBuilder.equal(root.get("Column2"), query.getColumn2()));
-
}
-
//联表操作
-
if(null != query.getColumn3()){
-
predicates.add(criteriaBuilder.equal(root.join("table1Column").get("Column3"), query.getColumn3()));
-
}
-
if(null != query.getColumn4()){
-
predicates.add(criteriaBuilder.equal(root.join("table1Column").get("Column4"), query.getColumn4()));
-
}
-
if(null != query.getColumn5()){
-
predicates.add(criteriaBuilder.equal(root.join("table1Column").get("Column5"), query.getColumn5()));
-
}
-
//拼接Sum
-
Expression<Integer> sumExpOne = criteriaBuilder.sum(criteriaBuilder.<Integer>selectCase().when(criteriaBuilder.equal(root.join("table1Column").get("Column6"), query.getColumn6()), 1).otherwise(0)).as(Integer.class);
-
Expression<Integer> sumExpTwo = criteriaBuilder.sum(criteriaBuilder.<Integer>selectCase().when(criteriaBuilder.isNull(root.join("table1Column").get("Column6")), 1).otherwise(0)).as(Integer.class);
-
//查询参数
-
List<Expression<?>> expressions = new ArrayList<Expression<?>>();
-
expressions.add(root.join("table1Column").get("Column1"));
-
//having参数
-
List<Predicate> predicateArrayList = new ArrayList<Predicate>();
-
Predicate predicate = criteriaBuilder.equal(sumExpOne,0);
-
predicate = criteriaBuilder.and(predicate,criteriaBuilder.greaterThan(sumExpTwo,0));
-
predicateArrayList.add(predicate);
-
//拼接SQL
-
criteriaQuery.multiselect(expressions.toArray(new Expression[expressions.size()])).distinct(true);
-
criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
-
criteriaQuery.groupBy(root.join("table1Column").get("Column1"));
-
criteriaQuery.having(predicateArrayList.toArray(new Predicate[predicateArrayList.size()]));
-
//获取第一次执行的结果
-
final List<Integer> list = entityManager.createQuery(criteriaQuery).getResultList();
-
Sort sort = new Sort(Sort.Direction.DESC, "id");
-
Pageable objectDao.findAll(new Specification<Object>(){
-
@Override
-
public Predicate toPredicate(Root<Object> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
-
//判断参数
-
List<Predicate> predicates = new ArrayList<Predicate>();
-
predicates.add(root.get("id").in(list));
-
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
-
}
-
},pageable);
-
}
上边代码里边很多column不对应,是为了隐去痕迹,方法已经测试通过,从上边的代码看spring data jpa对于复杂语句的支持不够,需要通过代码的方式实现,而这种方式代码的可读性会比较差,优化等都会有一些难度
最后总结一下就是如果业务简单实用spring data jpa即可,如果业务复杂还是实用mybatis吧
- spring data jpa还是只使用简单的操作
原文:https://blog.csdn.net/maoyeqiu/article/details/78752071
上一篇: c冒泡排序(小记)
下一篇: animation的小作用