这篇文章是我写的第二篇,写的不完美的地方 请各位前辈 指出! 谢谢!
此次发布一下 自己学习Many-TO-One 的过程,中途遇到几次错误,还好自己查资料等等,解决掉。
Hibernate 版本 : 5.3.7
Mysql 版本:8.0.13
jar包已上传,点击下载Hibernate+mysql jar包
创建好Java项目,导入上面的jar包,配置了hibernate.cgf.xml 文件 ,第一个是create创建表,查询数据库中后,要修改成update.避免每次都创建。
<!-- ~ Hibernate, Relational Persistence for Idiomatic Java ~ ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later. ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. -->
<!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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">数据库的密码</property>
<!--hibernate可选项 -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="format_sql">true</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<!--hbm文件 -->
<mapping resource="entity/Book_5_1.hbm.xml"/>
<mapping resource="entity/Publisher.hbm.xml"/>
<!-- 这是使用注解配置的方式,更换方式注意修改 mapping class or resource -->
<!-- <mapping class="entity.Orders"></mapping> -->
</session-factory>
</hibernate-configuration>
在src下创建entity (实体类)包,并创建实体类Book5_1
package entity;
import java.io.Serializable;
import java.util.Date;
public class Book_5_1 implements Serializable{
//注意: 实体类 实现序列化接口
private Long book_id;
private String isbn;
private String name;
private Publisher publisher;
private Date publisherDate;
private Integer price;
public Long getBook_id() {
return book_id;
}
public void setBook_id(Long book_id) {
this.book_id = book_id;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
public Date getPublisherDate() {
return publisherDate;
}
public void setPublisherDate(Date publisherDate) {
this.publisherDate = publisherDate;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
}
创建实体类Publisher(出版社),书在这里是多,出版社是一, 书-->出版社 (多-->一)的关系
package entity;
import java.io.Serializable;
public class Publisher implements Serializable{
private Long publisher_id;
private String code;
private String name;
private String address;
public Long getPublisher_id() {
return publisher_id;
}
public void setPublisher_id(Long publisher_id) {
this.publisher_id = publisher_id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
在这里我没有使用注解的方式,而是使用配置hbm.xml文件方式:
Book_5_1.hbm.xml文件: 因为多对一,书对出版社的关系,所以在书的配置文件中添加了<many-to-one>的标签
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2018-12-11 15:24:14 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="entity.Book_5_1" table="BOOK5">
<id name="book_id" type="java.lang.Long">
<column name="BOOK_ID" />
<generator class="native" />
</id>
<property name="isbn" type="java.lang.String">
<column name="ISBN" />
</property>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<property name="publisherDate" type="java.util.Date">
<column name="PUBLISHERDATE" />
</property>
<property name="price" type="java.lang.Integer">
<column name="PRICE" />
</property>
<many-to-one name="publisher" class="entity.Publisher" column="publisher_id" >
</many-to-one>
</class>
</hibernate-mapping>
配置Publisher.hbm.xml 文件,多对一关系, 出版社不用配置 many-to-one 的标签
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2018-12-11 15:24:14 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="entity.Publisher" table="PUBLISHER">
<id name="publisher_id" type="java.lang.Long">
<column name="PUBLISHER_ID" />
<generator class="native" />
</id>
<property name="code" type="java.lang.String">
<column name="CODE" />
</property>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<property name="address" type="java.lang.String">
<column name="ADDRESS" />
</property>
</class>
</hibernate-mapping>
工具类(dao),创建dao包,在其下创建HibernateUtil类:
package dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
//sessionfactory 消耗资源,所以放入代码块中加载一次 让配置文件加载一次
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.configure().build();
sessionFactory = new MetadataSources( serviceRegistry )
.buildMetadata().buildSessionFactory();
}
//得到当前的session
public static Session getCurrentSession() {
Session session = sessionFactory.openSession();
return session;
}
//关闭session
public static void closeSession(Session session)
{
if(session !=null)
{
session.close();
}
}
}
创建BOOK的工具类:
package dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import entity.Book_5_1;
public class BookDao {
public void addBook(Book_5_1 book)
{
//得到当前session并提交,增加一本书
Session session=HibernateUtil.getCurrentSession();
Transaction transaction=session.beginTransaction();
session.save(book);
transaction.commit();
HibernateUtil.closeSession(session);
}
//根据Id找到书
public Book_5_1 findById(long id)
{
Session session=HibernateUtil.getCurrentSession();
Book_5_1 book=(Book_5_1)session.get(Book_5_1.class, id);
//System.out.println(book.getPublisher().getName());
HibernateUtil.closeSession(session);
return book;
}
//获取全部书
public List<Book_5_1> getAllBook(){
Session session=HibernateUtil.getCurrentSession();
List<Book_5_1> books=session.createQuery("from Book_5_1").list();
return books;
}
}
创建PublisherDao 类
package dao;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import entity.Publisher;
public class PublisherDao {
public void addPublisher(Publisher publisher)
{
Session session=HibernateUtil.getCurrentSession();
Transaction transaction=session.beginTransaction();
session.persist(publisher);
transaction.commit();
HibernateUtil.closeSession(session);
}
public Publisher findById(long id) {
Session session=HibernateUtil.getCurrentSession();
Publisher publisher=(Publisher)session.load(Publisher.class,id );
HibernateUtil.closeSession(session);
return publisher;
}
}
Test (测试类:)
Session session=HibernateUtil.getCurrentSession();
session.beginTransaction();
//添加了一条出版社的记录
Publisher publisher = new Publisher();
publisher.setName("人民出版社");
publisher.setAddress("中关村南大街");
publisher.setCode("0001");
session.save(publisher);
session.getTransaction().commit();
HibernateUtil.closeSession(session);
控制台输出:
无错误,仔细看出现了create table ,然后在insert into,先创建在插入记录。回去看到hibernate 的配置文件发现还是create,没修改update,so 每次都先创建.
<property name="hbm2ddl.auto">create</property>
数据库查询生成记录,有了出版社,书绑定出版社。接着在test中
Book_5_1 book=new Book_5_1();
book.setIsbn("xx");
book.setName("java");
book.setPrice(50);
book.setPublisherDate(new Date());
PublisherDao pd=new PublisherDao();
publisher=pd.findById(1);
book.setPublisher(publisher); //设置关联关系书和出版社的关联
BookDao bd=new BookDao();
bd.addBook(book);
运行,一切正常:
查询数据库OK!!