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:

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

漁陽

彼此共勉,砥砺前行

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值