hibernate的bug

hibernate的作者自己说:他在编写hibernate的时候,对sql语言不理解,是现场看着书写完的程序,所以又bug就在所难免了。

 下面代码全部使用JPA

下面总结一下我碰到的bug:(不全,如果观者有其他的看法,请指出噢)

1、update 

eg:update User u set u.password =? where u.person.id=? 这种用法会出现错误

解决办法:

Person person = em.find(Person.class,1)

person.getUser().setPassword("123456");

 

2、当一个类中是复合主键的时候

airline 的主键为:复合主键 航班的主键为出发城市和到达城市(startCIty endCIty);

eg: select count(a) from ariline a  这样会出现错误。

 

解决办法:

要实现查询数量,可以使用sql语句为:select count(a.id.startCity) from airline a ;

下面的做法就是要实现通用的上面的这种用法。

	/**
	 * 计算实体的总记录数
	 * @param entityClass
	 * @return
	 */
	private <E> long getCount(Class<E> entityClass) throws Exception{
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("itcast");
		EntityManager em = factory.createEntityManager();
		String entityName = entityClass.getSimpleName();
		Entity entity = entityClass.getAnnotation(Entity.class);
		if(entity.name()!=null && !"".equals(entity.name())) entityName = entity.name();
		//如何得到所有属性
		PropertyDescriptor[] pdesc = Introspector.getBeanInfo(entityClass).getPropertyDescriptors();
		String filed = "o";
		for(PropertyDescriptor p : pdesc){
			Method method = p.getReadMethod();//获取属性的getter()方法
			if(method!=null && method.isAnnotationPresent(EmbeddedId.class)){//发现是一个复合主键类
				filed = filed+ "." + p.getName()+ ".";// o.id
				PropertyDescriptor[] idclassdesc = Introspector.getBeanInfo(p.getPropertyType()).getPropertyDescriptors();
				filed += idclassdesc[0].getName().equals("class") ? idclassdesc[1].getName() : idclassdesc[0].getName();
				break;
			}
		}
		//System.out.println(filed);
		long count = (Long)em.createQuery("select count("+ filed+ ") from "+ entityName+ " o").getSingleResult();
		em.close();
		factory.close();
		return count;
	}

 

你可能感兴趣的:(sql,Hibernate,jpa)