所需要的所有jar包:
antlr-2.7.7.jar
classmate-1.3.4.jar
dom4j-2.1.1.jar
hibernate-commons-annotations-5.0.1.Final.jar
hibernate-core-5.1.17.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
javassist-3.20.0-GA.jar
jboss-logging-3.3.0.Final.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
mysql-connector-java-5.1.47-bin.jar
以上所需jar包 提取码:giap
junit单元测试类:
package com.atguigu.hibernate.entites;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class Hibernate {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
@BeforeEach
public void init() {
Configuration configuration=new Configuration().configure();
sessionFactory=configuration.buildSessionFactory();
session=sessionFactory.getCurrentSession();
session=sessionFactory.openSession();
transaction=session.beginTransaction();
}
@AfterEach
public void destory() {
transaction.commit();
sessionFactory.close();
}
@Test
void test() {
News news=session.get(News.class, 3);
System.out.println(news);
}
}
javaBean类
package com.atguigu.hibernate.entites;
import java.util.Date;
public class News {
private Integer id;
private String title;
private String author;
private Date date;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public News(String title, String author, Date date) {
super();
this.title = title;
this.author = author;
this.date = date;
}
public News() {
super();
}
@Override
public String toString() {
return “News [id=” + id + “, title=” + title + “, author=” + author + “, date=” + date + “]”;
}
}
hibernate.cfg.xml配置信息
<?xml version="1.0" encoding="UTF-8"?> root ok com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/hibernate?useUnicode=true&useSSL=false&serverTimezone=UTC&characterEncoding=utf8 <!--配置hibernate基本信息 -->
<!--hibernate所使用的的數據庫方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!--執行操作時是否在控制台打印SQL -->
<property name="hibernate.show_sql">true</property>
<!--是否對SQL進行格式化 -->
<property name="hibernate.format_sql">true</property>
<!--指定自動生成數據表策略 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!--配置currentSession -->
<property name="hibernate.current_session_context_class">thread</property>
<!--指定關聯的.hbm.xml文件 -->
<mapping resource="com/atguigu/hibernate/entites/News.hbm.xml"/>
</session-factory>