Hibernate的简单的使用
(1)核心的配置文件(用来配置数据库的密码,显示sql语句,不同的数据库的方言,映射文件的位置等 hibernate.cfg.xml)
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="current_session_context_class">thread</property>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/westos?serverTimezone=GMT%2B8&useSSL=false&useServerPrepStmts=true&cachePrepStmts=true&rewriteBatchedStatements=true&useCursorFetch=true&defaultFetchSize=100&allowPublicKeyRetrieval=true</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="config/Account.hbm.xml"/>
</session-factory>
</hibernate-configuration>
(2)映射文件的配置(文件名:**.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.hibernate.pojo.Person" table="account">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name" column="name"></property>
<property name="money" column="money"></property>
</class>
</hibernate-mapping>
(3)测试类的编写
import com.hibernate.pojo.Person;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
public class TestHibernate {
@Test
public void test() {
Configuration configure = new Configuration().configure();
SessionFactory factory = configure.buildSessionFactory();
Session session = factory.openSession();
Transaction transaction = session.beginTransaction();
Person person = new Person();
person.setId(13);
person.setMoney(1000d);
person.setName("sunmoumou123456");
session.save(person);
transaction.commit();
session.close();
}
}