hibernate的集合映射demo:
前提介紹:
書籍Book【id,name,authors】,authors可能有N個,所以這裡用set表示;
實體類一個Book;表呢有兩個:tbook、tauthors;
1:model:
package model;import java.util.Set;public class Book {private int id;private String name;private Set<String> authors;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Set<String> getAuthors() {return authors;}public void setAuthors(Set<String> authors) {this.authors = authors;}}
2:Book的對應檔:hbm.xml
<class name="Book" table="TBook" lazy="false"> <id name="id"> <generator class="native"/> </id> <property name="name" column="bookName"/> <set name="authors" table="TAuthors"> <key column="id" /> <element column="authorName" type="string" not-null="true" length="30"/> </set> </class>
這裡有兩個地方需要稍微注意:
*寫明not-null="true"產生tauthors表時才會自動為你產生主鍵【id,authorName】,否則表沒有主鍵;
*指定length="30"如果不指定,會有以下ERROR,主鍵產生失敗;所以要指定小些;
not-null="true" length="30"
1218 [main] ERROR org.hibernate.tool.hbm2ddl.SchemaUpdate - Unsuccessful: create table TAuthors (id integer not null, topicName varchar(255) not null, primary key (id, topicName))1218 [main] ERROR org.hibernate.tool.hbm2ddl.SchemaUpdate - Specified key was too long; max key length is 767 bytes
3.DAO:
/** add */public void addPerson(Book p){Session session=null;Transaction tran=null;try {session=HibernateUtil.getSession();tran=session.beginTransaction();session.save(p);tran.commit();} catch (HibernateException e) {tran.rollback();e.printStackTrace();}finally{if(session!=null && session.isOpen()){session.close();}}}
4:service:
BookDao dao=new BookDao();/** add */public void add(Book p){dao.addPerson(p);}
5:JUnit 測試:
@Test public void testAdd() {Book p=new Book();p.setName("《Java核心技術》");Set<String> authors=new HashSet<String>();authors.add("Cay S.Horstmann");authors.add("Gary Cornell");p.setAuthors(authors);manager.add(p);}
6:最終資料庫結果:
mysql> select * from tbook;+----+------------------+| id | bookName |+----+------------------+| 1 | 《Java核心技術》 |+----+------------------+1 row in setmysql> select * from tauthors;+----+-----------------+| id | authorName |+----+-----------------+| 1 | Cay S.Horstmann || 1 | Gary Cornell |+----+-----------------+2 rows in set
表的ddl語句:
CREATE TABLE `tbook` ( `id` int(11) NOT NULL AUTO_INCREMENT, `bookName` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8--------------------------------------------------------------------CREATE TABLE `tauthors` ( `id` int(11) NOT NULL, `authorName` varchar(30) NOT NULL, PRIMARY KEY (`id`,`authorName`), KEY `FK529261547AAF8BC9` (`id`), CONSTRAINT `FK529261547AAF8BC9` FOREIGN KEY (`id`) REFERENCES `tbook` (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8
That's all;