本文共 2961 字,大约阅读时间需要 9 分钟。
package com.mycompany.demo.bean;public class Forum { private int fid; private String name; public Forum() { super(); } public Forum(String name) { super(); this.name = name; } public int getFid() { return fid; } public void setFid(int fid) { this.fid = fid; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + fid; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Forum other = (Forum) obj; if (fid != other.fid) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }}
This class contains the forum detail.
package com.mycompany.demo.util;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HbnUtil { private static SessionFactory sessionFactory; public static Session getSession(){ if(sessionFactory == null || sessionFactory.isClosed()){ sessionFactory = new Configuration().configure().buildSessionFactory(); } return sessionFactory.getCurrentSession(); }}
org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/b_shequ_two root update true true thread
package com.mycompany.demo.bean;import org.hibernate.Session;import org.hibernate.Transaction;import org.junit.Test;import com.mycompany.demo.util.HbnUtil;public class ManageForum { @Test public void testAdd(){ //1.获取Session Session session = HbnUtil.getSession(); Transaction transaction = null; try { //2.开启事务 transaction = session.beginTransaction(); //3.执行操作 Forum forum = new Forum("hbnutil"); session.save(forum); //4.提交事务 transaction.commit(); } catch (Exception e) { //5.回滚事务 if(transaction != null){ transaction.rollback(); } e.printStackTrace(); } }}
转载地址:http://ocell.baihongyu.com/