hibernate实现的简单插入与查询

好久没用过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:



org.hibernate.dialect.MySQLDialect
jdbc:mysql://localhost:3306/test2?"haracterEncoding"=gb2312
root
root
com.mysql.jdbc.Driver
mysql
true




User.hbm.xml:











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;
}
}



你可能感兴趣的:(javaWeb)