Hibernate

创建数据库表

create table user
(
    id       int auto_increment
        primary key,
    username varchar(50) null,
    password varchar(50) null,
    name     varchar(50) null
);

查看表


3.jpg

创建一个Java项目使用Maven

1.jpg

2.jpg

写pom.xml



    4.0.0

    org.example
    Hibernate
    1.0-SNAPSHOT

    
        8
        8
    
    
        
        
            org.hibernate
            hibernate-core
            5.4.31.Final
        
        
            log4j
            log4j
            1.2.12
        
        
            mysql
            mysql-connector-java
            5.1.6
        
    

创建实体类User

package main;

public class User {
    private int id;
    private String userName;
    private String passWord;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", passWord='" + passWord + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}

编写hibernate.cfg.xml



    
        com.mysql.jdbc.Driver
        jdbc:mysql://localhost:3306/spring?serverTimezone=Asia/Shanghai
        root
        123456
        true
        
    

编写user.hbm.xml




    
        
            
        
        
        
        
    

编写测试是类

package dao;

import main.User;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class mainUser {
    public static void main(String[] args){
        Configuration cfg = null;
        SessionFactory sf = null;
        Session session = null;
        Transaction ts = null;
        User u = new User();
        u.setUserName("wangwu");
        u.setPassWord("123456");
        u.setName("王五");
        try {
            cfg = new Configuration().configure();
            sf = cfg.buildSessionFactory();
            session = sf.openSession();
            ts = session.beginTransaction();
            session.save(u);
            ts.commit();
        }catch (HibernateException e){
            e.printStackTrace();
            if(ts != null){
                ts.rollback();
            }
        }finally {
            session.close();
            sf.close();
        }
    }
}

编写完成后的目录结构

4.jpg

运行测试

5.jpg

数据库查询

6.jpg

配置成功

你可能感兴趣的:(Hibernate)