首页 > 代码库 > Hibernate自动生成DO手写DAO的注意事项

Hibernate自动生成DO手写DAO的注意事项

自动生成DO,手写DAO:

Myeclipse添加Hibernate支持:注意别勾abstract

生成DO:进入MyEclipse的Database Explorer右键要操作的表(注意一定要有主键)点击Hibernate Reverse,其中Id选择native。

手写DAO:

Configuration con = new Configuration().configure();//构造核心类SessionFactory factory = con.buildSessionFactory();//连接工厂,这里的session相当于JDBC的connectionSession session = factory.openSession();//打开连接

增:思路:insert into tableName where XXX=? and XXX=?

Object objectName = new Object();//新建对象

objectName.setXXX("");//设置插入内容Transaction trans=session.beginTransaction();//完整事务session.save(objectName);trans.commit();//事务提交session.close();//关闭连接

删:思路:delete from tableName where id=?

Object objectName = new Object();
Transaction trans=session.beginTransaction();
objectName.setId(X); 

session.delete();

session.close();
trans.commit();

改:思路:update tableName set XXX=?, XXX=? where id=?

Object objectName = new Object();Transaction trans=session.beginTransaction();objectName.setId(X); session.update(objectName); session.close();trans.commit();

查:思路:select id as id, XXX as XXX, XXX as XXX from tableName where id=?

Object objectName  = (Object) session.get(Object.class, X);
session.close();

注:查找是不需要使用事务的。