1.The database returned no natively generated identity value
表主键未设置AUTO_INCREMENT
2.com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure Last packet sent to the server was 0 ms ago
严格说这不是hibernate的问题,而是数据库配置的问题,mysql的wait_timeout参数设置的问题。可以使用c3p0连接池来维持连接:
在hibernate.cfg.xml里增加:
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">1800</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">100</property>
<property name="hibernate.c3p0.acquire_increment">5</property>
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
3.一个对象ABean持有另一个对象BBean的引用,获取ABean对象的时候获取BBean。
public class ABean implements Serializable
{
private BBean b;
public BBean getB()
{
return reply;
}
public void setB(BBean b)
{
this.b = b;
}
...
}
在ABean.hbm.xml的配置里如下写:
<many-to-one name="reply" class="org.csdn.BBean" fetch="join" unique="true" update="true" insert="true" optimistic-lock="true" not-found="exception">
<column name="bId" />
</many-to-one>
4.有些hql无法执行,可以直接使用sql,例如:
public int[] getTotalAndRewaredCount()
{
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
// 创建事务
Transaction tx = session.beginTransaction();
String hql = "SELECT count(id) FROM T_CUSTOMER union all select count(status) from T_CUSTOMER where rewardTime is not null";
List lst = session.createSQLQuery(hql).list();
Iterator it = lst.iterator();
List<Integer> lstRes = new ArrayList<Integer>();
while (it.hasNext())
{
int c = Integer.parseInt(it.next().toString());
lstRes.add(c);
}
int s = lstRes.size();
int[] arr = new int[s];
for (int i = 0; i < s; i++)
{
arr[i] = lstRes.get(i);
}
tx.commit();
return arr;
}
5.取表部分字段
方法1:在Bean里添加部分字段的构造器,在获取的时候:
public List<MessageBean> retievePagedReplayedMessge(int start, int rows)
{
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session
.createQuery("select new MessageBean(msgId,leaveName,leaveTitle,leaveTime) from MessageBean where replyId is not null order by msgId desc");
query.setFirstResult(start);
query.setMaxResults(rows);
List<MessageBean> list = query.list();
tx.commit();
return list;
}
方法2: public List<CustomerBean> retrieveManageCustomers()
{
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
Criteria crit = session.createCriteria(CustomerBean.class);
crit.setProjection(Projections.projectionList().add(
Property.forName("registDate"), "registDate").add(
Property.forName("customerSource"), "customersource").add(
Property.forName("customerType"), "customertype").add(
Property.forName("customerStatus"), "customerstatus").add(
Property.forName("customerGrade"), "customergrade"));
List<CustomerBean> list = crit.list();
tx.commit();
return list;
}