Hibernate學習(一)建立資料表

lonecloud發表於2016-10-16

(1)生成資料庫表的建立:

1             // 預設讀取hibernate.cfg.xml檔案  
2             Configuration cfg = new Configuration().configure();  
3               
4             // 生成並輸出sql到檔案(當前目錄)和資料庫  
5             SchemaExport export = new SchemaExport(cfg);  
6               
7             // 建立表結構,第一個true 表示在控制檯列印sql語句,第二個true 表示匯入sql語句到資料庫
8             export.create(true, true); 

(2)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 <session-factory>
 8     <!-- 必須去配置的屬性 -->
 9     <!-- 配置資料庫連線的基本資訊: -->
10     <property name="hibernate.connection.driver_class">
11         com.mysql.jdbc.Driver
12     </property>
13     <property name="hibernate.connection.url">
14         jdbc:mysql:///hibernate
15     </property>
16     <property name="hibernate.connection.username">root</property>
17     <property name="hibernate.connection.password">123456</property>
18     <!-- Hibernate的方言 -->
19     <!-- 生成底層SQL不同的 -->
20     <property name="hibernate.dialect">
21         org.hibernate.dialect.MySQLDialect
22     </property>
23 
24     <!-- 可選的屬性 -->
25     <!-- 顯示SQL -->
26     <property name="hibernate.show_sql">true</property>
27     <!-- 格式化SQL -->
28     <property name="hibernate.format_sql">true</property>
29     <!-- hbm:對映 to DDL: create drop alter -->
30     <property name="hibernate.hbm2ddl.auto">update</property>
31 
32 
33     <!-- 通知Hibernate載入那些對映檔案 -->
34     <mapping resource="cn/lonecloud/domain/User.hbm.xml" />
35     <mapping resource="cn/lonecloud/domain/Customer.hbm.xml" />
36     <mapping resource="cn/lonecloud/domain/Order.hbm.xml" />
37 
38 </session-factory>
39 </hibernate-configuration>

(3)log4j.properties檔案

 1 ### direct log messages to stdout ###
 2 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
 3 log4j.appender.stdout.Target=System.err
 4 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
 5 log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
 6 
 7 ### direct messages to file mylog.log ###
 8 log4j.appender.file=org.apache.log4j.FileAppender
 9 log4j.appender.file.File=c\:mylog.log
10 log4j.appender.file.layout=org.apache.log4j.PatternLayout
11 log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
12 
13 ### set log levels - for more verbose logging change 'info' to 'debug' ###
14 
15 log4j.rootLogger=off, stdout 

(4)User.java

 1 package cn.lonecloud.domain;
 2 
 3 import java.io.Serializable;
 4 import java.lang.reflect.Field;
 5 import java.lang.reflect.Method;
 6 import java.util.Date;
 7 
 8 public class User implements Serializable,Cloneable {
 9    
10       private String id;
11       private String name;
12       private String password;
13       private Date birthday;
14       public User(){
15           System.out.println("user");
16       }
17     public String getId() {
18         return id;
19     }
20     public void setId(String id) {
21         this.id = id;
22     }
23     public String getName() {
24         return name;
25     }
26     public void setName(String name) {
27         this.name = name;
28     }
29     public String getPassword() {
30         return password;
31         
32     }
33     public void setPassword(String password) {
34         this.password = password;
35     }
36     public Date getBirthday() {
37         return birthday;
38     }
39     public void setBirthday(Date birthday) {
40         this.birthday = birthday;
41     }
42     @Override
43     public  Object clone() throws CloneNotSupportedException {
44          Class clazz = User.class;
45          User user =null;
46          try {
47              user = (User)clazz.newInstance();
48              /*user.setBirthday(this.birthday);
49              user.setId(this.id);
50              user.setPassword(this.password);
51              user.setName(this.name);*/
52              Field[] declaredFields = clazz.getDeclaredFields();
53              for(Field field :declaredFields){
54                   Class<?> parameterTypes = field.getType();
55                   String fieldName = field.getName();
56                   String methodName = "set"+fieldName.substring(0,1).toUpperCase()+field.getName().substring(1);
57                   Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
58                   field.setAccessible(true);
59                   method.invoke(user,field.get(this));
60              }
61              return user;
62         } catch (Exception e) {
63             e.printStackTrace();
64         } 
65          return null;
66     }
67       
68       
69 }

(5).user.hbm.xml

 1 <?xml version="1.0"?>  
 2 <!DOCTYPE hibernate-mapping PUBLIC   
 3     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
 4     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
 5 <hibernate-mapping package="cn.lonecloud.domain" >  
 6     <class name="User" table="t_user"  select-before-update="false">  
 7         <!--hibernate為我們生成主鍵id-->  
 8         <id name="id">  
 9             <generator class="uuid" />  
10         </id>  
11           
12         <!--預設把類的變數對映為相同名字的表列,當然我們使用column屬性修改表欄位-->  
13         <property name="name" column="names"></property>  
14         <property name="password"></property> 
15         <property name="birthday" type="date"></property> <!--當為日期型別的時候標明date型別-->
16         
17     </class>  
18 </hibernate-mapping>

 6.Customer.java

 1 package cn.lonecloud.domain;
 2 
 3 import java.io.Serializable;
 4 import java.util.HashSet;
 5 import java.util.Set;
 6 
 7 public class Customer implements Serializable {
 8 
 9     private String id;
10 
11     private String customerName;
12     
13     private Set<Order> orders = new HashSet<Order>();
14 
15     public String getId() {
16         return id;
17     }
18 
19     public void setId(String id) {
20         this.id = id;
21     }
22 
23     public String getCustomerName() {
24         return customerName;
25     }
26 
27     public void setCustomerName(String customerName) {
28         this.customerName = customerName;
29     }
30 
31     public Set<Order> getOrders() {
32         return orders;
33     }
34 
35     public void setOrders(Set<Order> orders) {
36         this.orders = orders;
37     }
38 
39     
40 }
View Code

7.Customer.hbm.xml

 1 <?xml version="1.0"?>  
 2 <!DOCTYPE hibernate-mapping PUBLIC   
 3     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
 4     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
 5 <hibernate-mapping package="cn.lonecloud.domain" >  
 6     <class name="Customer" table="t_customer" lazy="true">  
 7         <!--hibernate為我們生成主鍵id-->  
 8         <id name="id">  
 9             <generator class="uuid" />  
10         </id>  
11           
12         <!--預設把類的變數對映為相同名字的表列,當然我們使用column屬性修改表欄位-->  
13         <property name="customerName" column="customerName"></property>    
14         <set name="orders" lazy="extra" fetch="join" cascade="all-delete-orphan">  <!-- lazy fetch -->
15             <key column="customer_id"></key>
16             <one-to-many class="cn.lonecloud.domain.Order"/>
17         </set>
18         
19     </class>  
20 </hibernate-mapping>
View Code

8.Order.java

 1 package cn.lonecloud.domain;
 2 
 3 import java.io.Serializable;
 4 
 5 public class Order  implements Serializable{
 6  
 7      private String id;
 8      
 9      private String orderNumber;
10      
11      private float price;
12      
13      private Customer customer;
14      
15 
16     public Customer getCustomer() {
17         return customer;
18     }
19 
20     public void setCustomer(Customer customer) {
21         this.customer = customer;
22     }
23 
24     public String getId() {
25         return id;
26     }
27 
28     public void setId(String id) {
29         this.id = id;
30     }
31 
32     public String getOrderNumber() {
33         return orderNumber;
34     }
35 
36     public void setOrderNumber(String orderNumber) {
37         this.orderNumber = orderNumber;
38     }
39 
40     public float getPrice() {
41         return price;
42     }
43 
44     public void setPrice(float price) {
45         this.price = price;
46     }
47      
48      
49      
50      
51      
52 }
View Code

9.Order.hbm.xml

 1 <?xml version="1.0"?>  
 2 <!DOCTYPE hibernate-mapping PUBLIC   
 3     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
 4     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
 5 <hibernate-mapping package="cn.lonecloud.domain" >  
 6     <class name="Order" table="t_order" >  
 7         <!--hibernate為我們生成主鍵id-->  
 8         <id name="id">  
 9             <generator class="uuid" />  
10         </id>  
11           
12         <!--預設把類的變數對映為相同名字的表列,當然我們使用column屬性修改表欄位-->  
13         <property name="orderNumber" column="orderNumber"></property>    
14         <property name="price" column="price"></property>    
15         <many-to-one name="customer" class="cn.lonecloud.domain.Customer">
16            <column name="customer_id"/>
17         </many-to-one>
18     </class>  
19 </hibernate-mapping>
View Code

 

相關文章