62,623
社区成员
发帖
与我相关
我的任务
分享
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping SYSTEM "hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="per.dao.MyStudent" table="mystudent">
<id name="id" column="id" type="java.lang.Long">
<generator class="identity" />
</id>
<property name="name" type="string" column="name"/>
<property name="address" type="string" column="address" />
</class>
</hibernate-mapping>
package per.dao;
public class MyStudent{
private Long id;
public Long getId(){
return id;
}
public void setId(Long value){
this.id = id;
}
private String name = "";
public String getName(){
return name;
}
public void setName(String value){
name = value;
}
private String address = "";
public String getAddress(){
return address;
}
public void setAddress(String value){
address = value;
}
}
import org.hibernate.*;
import org.hibernate.cfg.*;
import per.dao.*;
class HibernateUtil {
public static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal<Session> session = new ThreadLocal<Session>();
public static Session currentSession() throws HibernateException {
Session s = session.get();
// Open a new Session, if this thread has none yet
if (s == null) {
s = sessionFactory.openSession();
// Store it in the ThreadLocal variable
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s = (Session) session.get();
if (s != null)
s.close();
session.set(null);
}
}
public class TestHibernate{
public static void main(String[] args){
Session session = HibernateUtil.currentSession();
Transaction trans = session.beginTransaction();
MyStudent stu = new MyStudent();
stu.setName("张三");
stu.setAddress("湖南");
session.save(stu);
trans.commit();
HibernateUtil.closeSession();
}
}