Hibernate 5.3.1.Final 增删改查

本文介绍了如何在Hibernate 5.3.1.Final环境下进行数据库的增删改查操作,包括环境配置、实体类创建、配置文件设置以及测试用例的详细步骤。通过SchemaExport自动建表,然后演示了新增、查询单条、查询列表、删除和更新等基本操作。
摘要由CSDN通过智能技术生成
Hibernate 5.3.1.Final 增删改查
1 环境信息

JDK:1.8
Hibernate:5.3.1.Final
Maven:3.2.5
OS:Win10

2 新建maven工程

2.1 pom.xml 添加依赖
点击查看

2.2 新建实体类 User
需要是个POJO:

public class User {
    private int id;
    private String name;
    private String phone;
    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 getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
}

2.3 新建hibernate配置文件hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>

    <session-factory>

        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        <property name="show_sql">true</property>

        <mapping resource="user.hbm.xml" />
    </session-factory>

</hibernate-configuration>

2.4 新建实体类映射配置文件User.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.wxx.entity.User" table="t_user">
        <id name="id">
            <generator class="assigned"></generator>
        </id>
        <property name="name"></property>
        <property name="phone"></property>
    </class>
</hibernate-mapping>

3 测试类

3.1 SchemaExport自动建表

@Test
    public void createTable() {
        ServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
        Metadata metadata = new MetadataSources(registry).buildMetadata();
        SchemaExport export = new SchemaExport();
        export.create(EnumSet.of(TargetType.DATABASE), metadata);
    }

执行后结果:

Hibernate: drop table if exists t_user
Hibernate: create table t_user (id integer not null, name varchar(255), phone varchar(255), primary key (id)) engine=InnoDB

查看数据库中,t_user表已经建好:
这里写图片描述


3.2 新增

@Test
    public void addUser() {
        // creating configuration object
        Configuration cfg = new Configuration();
        // populates the data of the configuration file
        cfg.configure("hibernate.cfg.xml");

        // creating seession factory object
        SessionFactory factory = cfg.buildSessionFactory();

        // creating session object
        Session session = factory.openSession();

        // creating transaction object
        Transaction t = session.beginTransaction();

        User user = new User();
        user.setId(102);
        user.setName("Weision");
        user.setPhone("3322326");

        // persisting the object
        // session.persist(user);
        // session.saveOrUpdate(user);
        session.save(user);

        t.commit();// transaction is committed
        session.close();

        System.out.println("successfully saved");

    }

执行后结果:

Hibernate: insert into t_user (name, phone, id) values (?, ?, ?)
successfully saved

这里写图片描述


3.3 查询单条

@Test
    public void queryUser() {
        Configuration cfg = new Configuration().configure();
        SessionFactory factory = cfg.buildSessionFactory();
        Session session = factory.openSession();
        Transaction t = session.beginTransaction();
        User user = session.get(User.class, 102);
        t.commit();
        session.close();
        System.out.println("successfully queryUser: name[" + user.getName() + "]。");
    }

3.4 查询列表
该操作前进行多次插入操作,以展示列表,准备数据如下:
这里写图片描述

 @Test
    public void queryUserList() {
        Configuration cfg = new Configuration().configure();
        SessionFactory factory = cfg.buildSessionFactory();
        Session session = factory.openSession();
        Transaction t = session.beginTransaction();
        @SuppressWarnings("unchecked")
        List<User> users = session.createQuery("from User").getResultList();
        int i = 0;
        for (User user : users) {
            System.out.println("queryUserList[" + i + "] name :[" + user.getName() + "]");
            i++;
        }
        t.commit();
        session.close();
    }

执行后结果:

Hibernate: select user0_.id as id1_2_, user0_.name as name2_2_, user0_.phone as phone3_2_ from t_user user0_
queryUserList[0] name :[Weision]
queryUserList[1] name :[Weision]
queryUserList[2] name :[Weision]
queryUserList[3] name :[Weision]
queryUserList[4] name :[Weision]

3.5 删除

@Test
    public void deleteUser() {
        Configuration cfg = new Configuration().configure();
        SessionFactory factory = cfg.buildSessionFactory();
        Session session = factory.openSession();
        Transaction t = session.beginTransaction();
        User user = new User();
        user.setId(0);
        user.setName("Weision");
        user.setPhone("3322326");

        session.delete(user);
        t.commit();
        session.close();
        System.out.println("successfully deleted");

    }

执行后结果:

Hibernate: select user_.id, user_.name as name2_2_, user_.phone as phone3_2_ from t_user user_ where user_.id=?
Hibernate: delete from t_user where id=?
successfully deleted

3.6 更新

@Test
    public void updateUser() {
        Configuration cfg = new Configuration().configure();
        SessionFactory factory = cfg.buildSessionFactory();
        Session session = factory.openSession();
        Transaction t = session.beginTransaction();
        User user = new User();
        user.setId(101);
        user.setName("Json");
        user.setPhone("3322326");

        session.update(user);
        t.commit();
        session.close();
        System.out.println("successfully deleted");

    }

执行后结果:

Hibernate: update t_user set name=?, phone=? where id=?
successfully deleted

这里写图片描述

工程代码:
点击跳转

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值