hibernate 非xml实体类配置方法!
这个是hibernate.cfg.xml配置文件
/p>
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
jdbc:mysql://localhost:3306/cms?useUnicode=true&characterEncoding=UTF-8
org.hibernate.dialect.MySQLDialect
root
1234
com.mysql.jdbc.Driver
View Code
其中 指向类名。
下面是这个类的代码,其中用了ITest注解。
packagecom.bird.entity;importjava.io.Serializable;importjavax.persistence.Entity;importjavax.persistence.Id;importjavax.persistence.Table;
@Entity
@Table(name= "i_test")public class ITest implementsSerializable {private static final long serialVersionUID = 1L;private intid;privateString name;
@Idpublic intgetId() {returnid;
}public void setId(intid) {this.id =id;
}publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}
}
View Code
最重要的是工具类 HibernateSessionFactory.java ,
因为采用了 Configuration configuration = new AnnotationConfiguration(); 这段代码创建Configuration ,所以才能不用去写实体类的xml配置文件了。
记住这个类:new AnnotationConfiguration();
(这个类要用 session.beginTransaction().commit(); 提交请求!)
TestUti.java 测试类代码,含有删改查功能
packagecom.bird.channel;importjava.util.Date;importjava.util.List;importorg.hibernate.Query;importorg.hibernate.Session;importcom.bird.entity.JcChannel;importcom.bird.entity.JcChannelExt;importcom.bird.entity.JcChnlGroupContri;importcom.bird.entity.JcSiteFlow;importcom.bird.util.HibernateSessionFactory;public classTestUtil {//查询的例子
public ListgetChannelList() {
Session session=HibernateSessionFactory.getSession();
String hql= "from JcChannel where parent_id is not null ";
Query query=session.createQuery(hql);
List jchList = (List) query.list();for (int i = 0; i < jchList.size(); i++) {
JcChannel jcEn=jchList.get(i);
System.out.println(jcEn.getChannel_id());
}returnjchList;
}//查询最大id的例子
public intgetChannelMaxIdByHql() {int id = 0;
Session session=HibernateSessionFactory.getSession();
String hql= "select max(channel_id) from JcChannel";
Query query=session.createQuery(hql);
List jchList=query.list();if (jchList.size() > 0) {
id= Integer.parseInt(jchList.get(0).toString());
}returnid;
}//查询最大id的例子
public intgetChannelMaxIdBySql() {int id = 0;
Session session=HibernateSessionFactory.getSession();
String hql= "select max(channel_id) from jc_channel ";
Query query=session.createSQLQuery(hql);
List jchList=query.list();if (jchList.size() > 0) {
id= Integer.parseInt(jchList.get(0).toString());
}returnid;
}//修改的例子
public intupdateChannelMaxId() {
Session session=HibernateSessionFactory.getSession();
String hql= "update jc_channel t set t.rgt = 2 ";
Query query=session.createSQLQuery(hql);int over =query.executeUpdate();
session.beginTransaction().commit();returnover;
}//删除的例子
public int deleteChannelMaxId(intid) {
Session session=HibernateSessionFactory.getSession();
String hql= "delete from jc_channel where channel_id = ? ";
Query query= session.createSQLQuery(hql).setParameter(0, id);int over =query.executeUpdate();
session.beginTransaction().commit();returnover;
}
}
View Code