package junit; import java.sql.Connection; import java.sql.SQLException; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.jdbc.Work; import org.junit.Test; import com.model.Student; public class SessionTest { @Test public void test1(){ Configuration configure = new Configuration().configure(); SessionFactory sessionFactory =configure.buildSessionFactory(); Session session = sessionFactory.openSession(); //System.out.println(session==session2); Transaction trans=session.beginTransaction(); session.doWork(new Work() { @Override public void execute(Connection arg0) throws SQLException { // TODO Auto-generated method stub System.out.println(arg0.hashCode()); } }); Student s = new Student(7, "kkk", new Date(), "上海"); session.save(s); trans.commit(); Session session2 = sessionFactory.openSession(); trans=session2.beginTransaction(); session2.doWork(new Work() { @Override public void execute(Connection arg0) throws SQLException { // TODO Auto-generated method stub System.out.println(arg0.hashCode()); } }); s = new Student(6, "111", new Date(), "上海"); session2.save(s); trans.commit(); session.close(); session2.close(); } }
你看看判断状态,改变状态的地方是不是有什么问题嘞。
理解是两个不同对象就好,估计你也使用的Java 8
hashCode方法是Object的方法 你是可以在任何子类里面复写的(java所有类均继承Object),如果手动设置 return “1"那就会相同
我也使用的hibernate5也是这样子,刚刚查了下Java中两个不同对象的hashcode可能相同
connection hashcode:1968552224
Hibernate:
insert
into
student
(sname, gender, birthday, address, sid)
values
(?, ?, ?, ?, ?)
connection hashcode:1968552224
false
Hibernate:
insert
into
student
(sname, gender, birthday, address, sid)
values
(?, ?, ?, ?, ?)
因为你显示的关闭了session会话,如果你注释掉,hashcode值就会不一样了,这也就是老师一直在证明opensesion()为什么不会自动关闭session会话,getCurrentSession()能自动关闭session会话了。我在评论区有具体说明。你可以去看下
不小心按了一个截图按钮。
console输出是这个:
Hibernate:
drop table if exists STUDENT
Hibernate:
create table STUDENT (
SID integer not null,
SNAME varchar(255),
BIRTHDAY datetime,
ADDRESS varchar(255),
primary key (SID)
)
Jun 30, 2016 10:04:40 PM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@a7e2d9d'
1215029765
Hibernate:
insert
into
STUDENT
(SNAME, BIRTHDAY, ADDRESS, SID)
values
(?, ?, ?, ?)
1215029765
Hibernate:
insert
into
STUDENT
(SNAME, BIRTHDAY, ADDRESS, SID)
values
(?, ?, ?, ?)