文章目录
sql
create database hibernateTest;
use hibernateTest;
create table user
(
`id` int not null primary key,
`name` varchar(200) not null,
`sex` varchar(200) not null
)
User.java
package com.cai.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Description
* @Author Cai
* @Date 2021-04-01 13:49
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer id;
private String name;
private String sex;
}
User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.cai.domain">
<class name="User" table="user">
<id name="id" type="java.lang.Integer">
<generator class="identity"/>
</id>
<property name="name"/>
<property name="sex"/>
</class>
</hibernate-mapping>
UserManager
package com.cai;
import com.cai.domain.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
/**
* @Description
* @Author Cai
* @Date 2021-04-01 13:53
*/
public class UserManager {
public static void main(String[] args) throws Exception{
Configuration conf = new Configuration().configure();
SessionFactory sessionFactory = conf.buildSessionFactory();
Session sess = sessionFactory.openSession();
Transaction startTask = sess.beginTransaction();
User user = new User();
user.setName("wade");
user.setSex("bad boy");
sess.save(user);
startTask.commit();
sessionFactory.close();
}
}
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernateTest</property>
<property name="connection.username">root</property>
<property name="connection.password">818181</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping resource="com/cai/domain/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
结果
遇到的问题
Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
这个的话,我的情况是缺少了javassist的包,所以在依赖那里加了这个包就行了