实体类与表对应文件Customer.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>
<!– 建立与表的映射 –>
<class name=”com.Inf.Customer” table=”cst_customer”>
<id name=”cust_id” column=”cust_id”>
<generator class=”native”></generator>
</id>
<property name=”cust_name” column=”cust_name” length=”32″></property>
<property name=”cust_leve” column=”cust_leve” length=”32″></property>
<property name=”cust_phone” column=”cust_phone” length=”32″></property>
<property name=”cust_industry” column=”cust_industry” length=”32″></property>
<property name=”cust_mobile” column=”cust_mobile” length=”32″></property>

</class>
</hibernate-mapping>

 

 

 

 

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>
<!– jdbc:mysql://localhost:3306/hibernate?serverTimezone=UTC –>
<session-factory>
<property name=”hibernate.connection.driver_class”>com.mysql.cj.jdbc.Driver</property>
<property name=”hibernate.connection.url”>
<![CDATA[jdbc:mysql://localhost:3306/hibernate?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8]]>
</property>
<property name=”hibernate.connection.username”>root</property>
<property name=”hibernate.connection.password”>root</property>
<!– 方言 –>
<property name=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</property>
<!– 打印sql –>
<property name=”hibernate.show_sql”>true</property>
<!– 格式化sql –>
<property name=”hibernate.format_sql”>true</property>
<!–自动建表 –>
<property name=”hibernate.hbm2ddl.auto”>update</property>
<!– 加载配置文件 –>
<mapping resource=”com/Inf/Customer.hbm.xml”/>

</session-factory>
</hibernate-configuration>

测试类====

package com.Inf;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class HibernateDemo {
@Test
public void demo1() {
System.out.println(“进入程序”);
//1.加载ibernate核心配置
Configuration configuration =new Configuration().configure();
//2。创建一个sessionfactory对象 相当于jdbc连接池
SessionFactory sessionFactory=configuration.buildSessionFactory();
//3.ͨ通过sessionfactory获取jdbc
Session session =sessionFactory.openSession();
//4.手动开启事务
Transaction transaction =session.beginTransaction();
//5.编写代码
Customer customer=new Customer();
customer.setCust_name(“国家”);
session.save(customer);
System.out.println(“保存结束”);
//6.事务提交
transaction.commit();
//7.关闭资源
session.close();
sessionFactory.close();
}

}

 

版权声明:本文为xianz666原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/xianz666/p/12745164.html