zoukankan      html  css  js  c++  java
  • (六)Hibernate 映射类型

    所有项目导入对应的hibernate的jar包、mysql的jar包和添加每次都需要用到的HibernateUtil.java

    第一节:基本类型映射

     

     例子:

    hibernate.cfg.xml

     1 <?xml version='1.0' encoding='utf-8'?>
     2 <!DOCTYPE hibernate-configuration PUBLIC
     3         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     4         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
     5 
     6 <hibernate-configuration>
     7 
     8     <session-factory>
     9 
    10         <!--数据库连接设置 -->
    11         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    12         <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
    13         <property name="connection.username">root</property>
    14         <property name="connection.password">123456</property>
    15 
    16        
    17         <!-- 方言 -->
    18         <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
    19     
    20         <!-- 控制台显示SQL -->
    21         <property name="show_sql">true</property>
    22 
    23         <!-- 自动更新表结构 -->
    24         <property name="hbm2ddl.auto">update</property>
    25         
    26           <mapping resource="com/wishwzp/model/Student.hbm.xml"/>
    27           
    28           <mapping resource="com/wishwzp/model/Book.hbm.xml"/>
    29 
    30     </session-factory>
    31 
    32 </hibernate-configuration>

    Book.java

     1 package com.wishwzp.model;
     2 
     3 import java.sql.Blob;
     4 import java.util.Date;
     5 
     6 public class Book {
     7 
     8     private int id;
     9     private String bookName; // 图书名称
    10     private float price; // 图书价格
    11     private boolean specialPrice; // 是否是特价
    12     private Date publishDate; // 发布日期
    13     private String author; // 作者
    14     private String introduction; // 简介
    15     private Blob bookPic; // 图书图片
    16     
    17     public int getId() {
    18         return id;
    19     }
    20     public void setId(int id) {
    21         this.id = id;
    22     }
    23     public String getBookName() {
    24         return bookName;
    25     }
    26     public void setBookName(String bookName) {
    27         this.bookName = bookName;
    28     }
    29     public float getPrice() {
    30         return price;
    31     }
    32     public void setPrice(float price) {
    33         this.price = price;
    34     }
    35     public boolean isSpecialPrice() {
    36         return specialPrice;
    37     }
    38     public void setSpecialPrice(boolean specialPrice) {
    39         this.specialPrice = specialPrice;
    40     }
    41     public Date getPublishDate() {
    42         return publishDate;
    43     }
    44     public void setPublishDate(Date publishDate) {
    45         this.publishDate = publishDate;
    46     }
    47     public String getAuthor() {
    48         return author;
    49     }
    50     public void setAuthor(String author) {
    51         this.author = author;
    52     }
    53     public String getIntroduction() {
    54         return introduction;
    55     }
    56     public void setIntroduction(String introduction) {
    57         this.introduction = introduction;
    58     }
    59     public Blob getBookPic() {
    60         return bookPic;
    61     }
    62     public void setBookPic(Blob bookPic) {
    63         this.bookPic = bookPic;
    64     }
    65     
    66     
    67     
    68 }

    Book.hbm.xml

     1 <?xml version="1.0"?>
     2 <!DOCTYPE hibernate-mapping PUBLIC
     3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     4         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
     5 
     6 <hibernate-mapping package="com.wishwzp.model">
     7 
     8     <class name="Book" table="t_book">
     9         <id name="id" column="bookId">
    10             <generator class="native"></generator>
    11         </id>
    12         
    13         <property name="bookName" column="bookName" length="40"></property>
    14         <property name="price" column="price" type="float"></property>
    15         <property name="specialPrice" column="specialPrice" type="boolean"></property>
    16         <property name="publishDate" column="publishDate" type="date"></property>
    17         <property name="author" column="author" length="20"></property>
    18         <property name="introduction" column="introduction" type="text"></property>
    19         <property name="bookPic" column="bookPic" type="blob"></property>
    20     </class>
    21 
    22 </hibernate-mapping>

     BookTest.java

     1 package com.wishwzp.service;
     2 
     3 import java.io.FileInputStream;
     4 import java.io.InputStream;
     5 import java.sql.Blob;
     6 import java.text.SimpleDateFormat;
     7 
     8 import org.hibernate.LobHelper;
     9 import org.hibernate.Session;
    10 import org.hibernate.SessionFactory;
    11 
    12 import com.wishwzp.model.Book;
    13 import com.wishwzp.util.HibernateUtil;
    14 
    15 public class BookTest {
    16     
    17     public static void main(String[] args) throws Exception{
    18         SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
    19         Session session=sessionFactory.openSession(); // 生成一个session
    20         session.beginTransaction(); // 开启事务
    21         
    22         Book book=new Book();
    23         book.setBookName("java编程思想");
    24         book.setPrice(100);
    25         book.setSpecialPrice(true);
    26         book.setPublishDate(new SimpleDateFormat("yyyy-MM-dd").parse("2013-1-1"));
    27         book.setAuthor("埃克尔");
    28         book.setIntroduction("简介...");
    29         
    30         //
    31         LobHelper lobHelper=session.getLobHelper();
    32         InputStream in=new FileInputStream("c://java编程思想.jpg");
    33         Blob bookPic=lobHelper.createBlob(in, in.available());
    34         book.setBookPic(bookPic);
    35        
    36         session.save(book);
    37         
    38         session.getTransaction().commit(); // 提交事务
    39         session.close(); // 关闭session
    40      
    41     }
    42 }

     HibernateUtil.java

     1 package com.wishwzp.util;
     2 
     3 import org.hibernate.SessionFactory;
     4 import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
     5 import org.hibernate.cfg.Configuration;
     6 import org.hibernate.service.ServiceRegistry;
     7 
     8 /**
     9  * 
    10  * hibernate封装
    11  * @author wishwzp
    12  *
    13  */
    14 public class HibernateUtil {
    15     
    16     private static final SessionFactory sessionFactory=buildSessionFactory();
    17 
    18     /**
    19      * 绑定SessionFactory
    20      * @return
    21      */
    22     private static SessionFactory buildSessionFactory(){
    23         // 实例化配置文件
    24         Configuration configuration=new Configuration().configure(); 
    25         // 实例化服务登记
    26         ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    27         //获取Session工厂
    28         return configuration.buildSessionFactory(serviceRegistry);
    29     }
    30     
    31     public static SessionFactory getSessionFactory(){
    32         return sessionFactory;
    33     }
    34 }

    第二节:集合类型映射

    hibernate.cfg.xml

     1 <?xml version='1.0' encoding='utf-8'?>
     2 <!DOCTYPE hibernate-configuration PUBLIC
     3         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     4         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
     5 
     6 <hibernate-configuration>
     7 
     8     <session-factory>
     9 
    10         <!--数据库连接设置 -->
    11         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    12         <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
    13         <property name="connection.username">root</property>
    14         <property name="connection.password">123456</property>
    15 
    16        
    17         <!-- 方言 -->
    18         <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
    19     
    20         <!-- 控制台显示SQL -->
    21         <property name="show_sql">true</property>
    22 
    23         <!-- 自动更新表结构 -->
    24         <property name="hbm2ddl.auto">update</property>
    25         
    26           <mapping resource="com/wishwzp/model/Student.hbm.xml"/>
    27           <mapping resource="com/wishwzp/model/Student2.hbm.xml"/>
    28           <mapping resource="com/wishwzp/model/Student3.hbm.xml"/>
    29           <mapping resource="com/wishwzp/model/Student4.hbm.xml"/>
    30 
    31     </session-factory>
    32 
    33 </hibernate-configuration>

    1,Set 无序元素不可重复

    Student.java

     1 package com.wishwzp.model;
     2 
     3 import java.util.Set;
     4 
     5 public class Student {
     6 
     7     private long id;
     8     private String name;
     9     private Set<String> images;
    10     
    11     public long getId() {
    12         return id;
    13     }
    14     public void setId(long id) {
    15         this.id = id;
    16     }
    17     public String getName() {
    18         return name;
    19     }
    20     public void setName(String name) {
    21         this.name = name;
    22     }
    23     public Set<String> getImages() {
    24         return images;
    25     }
    26     public void setImages(Set<String> images) {
    27         this.images = images;
    28     }
    29     
    30     
    31     
    32     
    33 }

    Student.hbm.xml

     1 <?xml version="1.0"?>
     2 <!DOCTYPE hibernate-mapping PUBLIC
     3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     4         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
     5 
     6 <hibernate-mapping package="com.wishwzp.model">
     7 
     8     <class name="Student" table="t_student">
     9         <id name="id" column="stuId">
    10             <generator class="native"></generator>
    11         </id>
    12         
    13         <property name="name" column="stuName"></property>
    14         
    15         <set name="images" table="t_image">
    16             <key column="studentId"></key>
    17             <element column="imageName" type="string"></element>
    18         </set>
    19     </class>
    20 
    21 </hibernate-mapping>

    2,List 有序元素可重复

    Studnet2.java

     1 package com.wishwzp.model;
     2 
     3 import java.util.List;
     4 
     5 public class Student2 {
     6 
     7     private long id;
     8     private String name;
     9     private List<String> images;
    10     
    11     public long getId() {
    12         return id;
    13     }
    14     public void setId(long id) {
    15         this.id = id;
    16     }
    17     public String getName() {
    18         return name;
    19     }
    20     public void setName(String name) {
    21         this.name = name;
    22     }
    23     public List<String> getImages() {
    24         return images;
    25     }
    26     public void setImages(List<String> images) {
    27         this.images = images;
    28     }
    29     
    30 }

    Student2.hbm.xml

     1 <?xml version="1.0"?>
     2 <!DOCTYPE hibernate-mapping PUBLIC
     3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     4         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
     5 
     6 <hibernate-mapping package="com.wishwzp.model">
     7 
     8     <class name="Student2" table="t_student">
     9         <id name="id" column="stuId">
    10             <generator class="native"></generator>
    11         </id>
    12         
    13         <property name="name" column="stuName"></property>
    14         
    15         <list name="images" table="t_image2">
    16             <key column="studentId"></key>
    17             <list-index column="imageIndex"></list-index>
    18             <element column="imageName" type="string"></element>
    19         </list>
    20     </class>
    21 
    22 </hibernate-mapping>

    3,Bag 无序元素可重复

    Student3.java

     1 package com.wishwzp.model;
     2 
     3 import java.util.List;
     4 
     5 public class Student3 {
     6 
     7     private long id;
     8     private String name;
     9     private List<String> images;
    10     
    11     public long getId() {
    12         return id;
    13     }
    14     public void setId(long id) {
    15         this.id = id;
    16     }
    17     public String getName() {
    18         return name;
    19     }
    20     public void setName(String name) {
    21         this.name = name;
    22     }
    23     public List<String> getImages() {
    24         return images;
    25     }
    26     public void setImages(List<String> images) {
    27         this.images = images;
    28     }
    29     
    30 }

    Student3.hbm.xml

     1 <?xml version="1.0"?>
     2 <!DOCTYPE hibernate-mapping PUBLIC
     3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     4         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
     5 
     6 <hibernate-mapping package="com.wishwzp.model">
     7 
     8     <class name="Student3" table="t_student">
     9         <id name="id" column="stuId">
    10             <generator class="native"></generator>
    11         </id>
    12         
    13         <property name="name" column="stuName"></property>
    14         
    15         <idbag name="images" table="t_image3">
    16             <collection-id type="long" column="imageId">
    17                 <generator class="increment"></generator>
    18             </collection-id>
    19             <key column="studentId"></key>
    20             <element column="imageName" type="string"></element>
    21         </idbag>
    22         
    23     
    24     </class>
    25 
    26 </hibernate-mapping>

    4,Map 键值对

    Student4.java

     1 package com.wishwzp.model;
     2 
     3 import java.util.Map;
     4 
     5 public class Student4 {
     6 
     7     private long id;
     8     private String name;
     9     private Map<String,String> images;
    10     
    11     public long getId() {
    12         return id;
    13     }
    14     public void setId(long id) {
    15         this.id = id;
    16     }
    17     public String getName() {
    18         return name;
    19     }
    20     public void setName(String name) {
    21         this.name = name;
    22     }
    23     public Map<String, String> getImages() {
    24         return images;
    25     }
    26     public void setImages(Map<String, String> images) {
    27         this.images = images;
    28     }
    29     
    30 }

    Student4.hbm.xml 

     1 <?xml version="1.0"?>
     2 <!DOCTYPE hibernate-mapping PUBLIC
     3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     4         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
     5 
     6 <hibernate-mapping package="com.wishwzp.model">
     7 
     8     <class name="Student4" table="t_student">
     9         <id name="id" column="stuId">
    10             <generator class="native"></generator>
    11         </id>
    12         
    13         <property name="name" column="stuName"></property>
    14         
    15         <map name="images" table="t_image4">
    16             <key column="studentId"></key>
    17             <map-key column="imageKey" type="string"></map-key>
    18             <element column="imageName" type="string"></element>
    19         </map>
    20         
    21     
    22     </class>
    23 
    24 </hibernate-mapping>

    上面4种情况的总测试类:

    StudentTest.java

      1 package com.wishwzp.service;
      2 
      3 import java.util.ArrayList;
      4 import java.util.HashMap;
      5 import java.util.HashSet;
      6 import java.util.Iterator;
      7 import java.util.List;
      8 import java.util.Map;
      9 import java.util.Set;
     10 
     11 import org.hibernate.Session;
     12 import org.hibernate.SessionFactory;
     13 import org.junit.After;
     14 import org.junit.Before;
     15 import org.junit.Test;
     16 
     17 import com.wishwzp.model.Student;
     18 import com.wishwzp.model.Student2;
     19 import com.wishwzp.model.Student3;
     20 import com.wishwzp.model.Student4;
     21 import com.wishwzp.util.HibernateUtil;
     22 
     23 public class StudentTest {
     24 
     25     private SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
     26     private Session session;
     27     
     28     @Before
     29     public void setUp() throws Exception {
     30         session=sessionFactory.openSession(); // 生成一个session
     31         session.beginTransaction(); // 开启事务
     32     }
     33 
     34     @After
     35     public void tearDown() throws Exception {
     36          session.getTransaction().commit(); // 提交事务
     37          session.close(); // 关闭session
     38     }
     39 
     40     //1、Set 无序元素不可重复
     41     @Test
     42     public void testSetSave(){
     43         Set<String> imageSet=new HashSet<String>();
     44         imageSet.add("image1.png");
     45         imageSet.add("image2.png");
     46         imageSet.add("image3.png");
     47         imageSet.add("image3.png");//这里有重复,但在数据库里面只有一个image3.png并且是无序的。。。所以set元素不可重复
     48         
     49         Student s1=new Student();
     50         s1.setImages(imageSet);
     51         session.save(s1);
     52     }
     53     
     54     //打印出来Student表id为1的images表的所有image信息
     55     @Test
     56     public void testSetFetch(){
     57         Student student=(Student)session.get(Student.class, Long.valueOf(1));
     58         Iterator it=student.getImages().iterator();
     59         while(it.hasNext()){
     60             System.out.println(it.next());
     61         }
     62     }
     63     
     64     //2、List 有序元素可重复
     65     @Test
     66     public void testListSave(){
     67         List<String> imageList=new ArrayList<String>();
     68         imageList.add("image1.png");
     69         imageList.add("image2.png");
     70         imageList.add("image3.png");
     71         imageList.add("image3.png");//这里有重复,数据库里面也可以有两个image3.png并且是有序的。。。所以list元素可重复
     72         
     73         Student2 s2=new Student2();
     74         s2.setImages(imageList);
     75         session.save(s2);
     76     }
     77     
     78     //打印出来Student表id为1的images表的所有image信息
     79     @Test
     80     public void testListFetch(){
     81         Student2 student2=(Student2)session.get(Student2.class, Long.valueOf(2));
     82         Iterator it=student2.getImages().iterator();
     83         while(it.hasNext()){
     84             System.out.println(it.next());
     85         }
     86     }
     87     
     88     //3、Bag 无序元素可重复
     89     @Test
     90     public void testBagSave(){
     91         List<String> imageList=new ArrayList<String>();
     92         imageList.add("image1.png");
     93         imageList.add("image2.png");
     94         imageList.add("image3.png");
     95         imageList.add("image3.png");//这里有重复,数据库里面也有两个image3.png而且是无序的。。。所以Bag 无序元素可重复
     96         
     97         Student3 s3=new Student3();
     98         s3.setImages(imageList);
     99         session.save(s3);
    100     }
    101     
    102     
    103     @Test
    104     public void testBagFetch(){
    105         Student3 student3=(Student3)session.get(Student3.class, Long.valueOf(3));
    106         Iterator it=student3.getImages().iterator();
    107         while(it.hasNext()){
    108             System.out.println(it.next());
    109         }
    110     }
    111     
    112     //4、Map 键值对
    113     @Test
    114     public void testMapSave(){
    115         Map<String,String> imageMap=new HashMap<String,String>();
    116         imageMap.put("i1", "image1.png");
    117         imageMap.put("i2", "image2.png");
    118         imageMap.put("i3", "image3.png");
    119         imageMap.put("i4", "image4.png");//这里都是键值对的
    120         
    121         Student4 s4=new Student4();
    122         s4.setImages(imageMap);
    123         session.save(s4);
    124     }
    125     
    126     
    127     @Test
    128     public void testMapFetch(){
    129         Student4 student4=(Student4)session.get(Student4.class, Long.valueOf(4));
    130         Map<String,String> imageMap=student4.getImages();
    131         Set keys=imageMap.keySet();
    132         Iterator it=keys.iterator();
    133         while(it.hasNext()){
    134             String key=(String)it.next();
    135             System.out.println(key+":"+imageMap.get(key));
    136         }
    137     }
    138 
    139 }

    结果显示:

    1,Set 无序元素不可重复

    testSetSave()方法:



    testSetFech()方法:

    2,List 有序元素可重复

    testListSave()方法:



    testListFech()方法:

    3,Bag 无序元素可重复

    testBagSave()方法:



    testBagFech()方法:

    4,Map 键值对

    testMapSave()方法:



    testMapFech()方法:

    所有表之间的关系:

  • 相关阅读:
    jquery的ready和简写
    javasript之ajax学习笔记
    用 Drupal 创建更好的评分系统的具体步骤
    drupal的FIVESTAR投票模块说明
    drupal中时间自定义格式
    drupal首页不显示默认内容列表方法
    基于 Zen 创建一个 Drupal 7 的主题(模板) ,一份简单的Drupal模板教程
    jquery tooltip事件
    HTML5地区自转代码
    转:Jmeter常见问题 (转载) http://www.51testing.com/?uid-128005-action-viewspace-itemid-84094
  • 原文地址:https://www.cnblogs.com/wishwzp/p/5481270.html
Copyright © 2011-2022 走看看