创建数据库
CREATE DATABASE IF NOT EXISTS ` hibernate_day1` ;
USE ` hibernate_day1` ;
CREATE TABLE IF NOT EXISTS ` t_user` (
` id` int NOT NULL AUTO_INCREMENT ,
` username` varchar ( 50 ) NOT NULL DEFAULT '0' ,
` password` varchar ( 30 ) NOT NULL DEFAULT '0' ,
PRIMARY KEY ( ` id` )
) ENGINE = InnoDB AUTO_INCREMENT = 4 DEFAULT CHARSET = utf8;
编写实体类
package org. ccit. com. domain;
public class User {
private int uid;
private String username;
private String password;
public int getUid ( ) {
return uid;
}
public void setUid ( int uid) {
this . uid = uid;
}
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;
}
}
在实体类同级目录下创建实体类名.hbm.xml映射配置文件
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
< hibernate-mapping>
< class name = " org.ccit.com.domain.User" table = " t_user" >
< id name = " uid" column = " id" >
< generator class = " native" > </ generator>
</ id>
< property name = " username" > </ property>
< property name = " password" > </ property>
</ class>
</ hibernate-mapping>
创建hibernate.cfg.xml核心配置文件
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
< hibernate-configuration>
< session-factory>
< property name = " hibernate.connection.driver_class" > com.mysql.cj.jdbc.Driver</ property>
< property name = " hibernate.connection.url" > jdbc:mysql:///hibernate_day1?serverTimezone=UTC& useSSL=false</ property>
< property name = " hibernate.connection.username" > root</ property>
< property name = " hibernate.connection.password" > 123456</ property>
< property name = " show_sql" > true</ property>
< property name = " format_sql" > true</ property>
< property name = " hibernate.connection.autocommit" > true</ property>
< mapping resource = " org/ccit/com/domain/User.hbm.xml" />
</ session-factory>
</ hibernate-configuration>
编写Test类测试
import org. ccit. com. domain. User;
import org. hibernate. SessionFactory;
import org. hibernate. Transaction;
import org. hibernate. cfg. Configuration;
import org. hibernate. classic. Session;
import org. junit. Test;
import java. sql. Connection;
public class HibernateTest01 {
@Test
public void test01 ( ) {
Configuration configure = new Configuration ( ) . configure ( ) ;
SessionFactory sessionFactory = configure. buildSessionFactory ( ) ;
Session session = sessionFactory. openSession ( ) ;
Transaction transaction = session. getTransaction ( ) ;
transaction. begin ( ) ;
User user = new User ( ) ;
user. setUsername ( "LIANG" ) ;
user. setPassword ( "2233" ) ;
session. save ( user) ;
transaction. commit ( ) ;
session. close ( ) ;
sessionFactory. close ( ) ;
}
}