ORM1-使用Hibernate实现用户添加

1:导入Hibernate库在这里插入图片描述
2:添加配置文件 – hibernate.cfg.xml
<hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hellohibernate?useSSL=false</property> <property name="hibernate.connection.username"></property>//用户名 <property name="hibernate.connection.password"></property>//密码 <property name="show_sql">true</property> <mapping resource="cn/hrbust/pojo/User.hbm.xml"/> </session-factory> </hibernate-configuration>
3:添加实体类和映射文件
import java.util.Date;
public class User {
private int id;
private String name;
private String gender;
int age;
Date birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
设计数据库:
在这里插入图片描述
导入User.hbm.xml

测试:创建manageUser.java
import java.sql.Date;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import cn.hrbust.pojo.User;
public class manageUser {
public static void main(String[] args) {
// TODO Auto-generated method stub
Configuration cfg = null;
SessionFactory sf = null;
Session session = null;
Transaction ts = null;
User u = new User();
u.setName(“ztr”);//添加名字
u.setGender(“男”);//添加性别
u.setAge(21);//添加年龄
u.setBirthday(Date.valueOf(“2000-4-1”));//添加生日
try {
cfg = new Configuration().configure();
sf = cfg.buildSessionFactory();
session = sf.openSession();
ts = session.beginTransaction();
session.save(u);
ts.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if(ts != null) {
ts.rollback();
}
} finally {
session.close();
sf.close();
}
}
}
数据库中添加成功:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值