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 set mysql> 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;