好久没用过hibernate了,今天就写一下hibernate的简单操作。
一:插入的实现
1)、
public static void main(String[] args) {
User user = new User();
user.setUsername("Haibin");
user.setPass("hello");
Session session = HibernateSessionFactory.getSession();
Transaction tracsaction = null;
try {
tracsaction = (Transaction) session.beginTransaction();
session.save(user);
tracsaction.commit();
System.out.println("添加成功!");
} catch (Exception e) {
e.printStackTrace();
tracsaction.rollback();
}
HibernateSessionFactory.closeSession();
}
2)、上面中HibernateSessionFactory,与Trancscation完成与数据库的关联和操作。通过HibernateSessionFactory加载hibernate.cfg.xml,通过此xml加载对应的model.hbm.ximl.
3)、hibernate.cfg.xml:
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test2?"haracterEncoding"=gb2312</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="myeclipse.connection.profile">mysql</property>
<property name="show_sql">true</property>
<mapping resource="po/Student.hbm.xml" />
<mapping resource="po/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
User.hbm.xml:
<hibernate-mapping>
<class name="po.User">
<id name="username">
<generator class="assigned"></generator>
</id>
<property name="pass"></property>
</class>
</hibernate-mapping>
4)、User.java(model)
package po;
public class Student {
private String id;
private String name;
private String sunject;
private double result;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSunject() {
return sunject;
}
public void setSunject(String sunject) {
this.sunject = sunject;
}
public double getResult() {
return result;
}
public void setResult(double result) {
this.result = result;
}
}