关闭

hibernate实现的简单插入与查询

标签: java
172人阅读 评论(0) 收藏 举报
分类:

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



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:47814次
    • 积分:2129
    • 等级:
    • 排名:第17953名
    • 原创:162篇
    • 转载:40篇
    • 译文:2篇
    • 评论:3条
    最新评论