Hibernate 一对多双向映射 代码

来源:互联网 发布:java字典表 编辑:程序博客网 时间:2024/05/17 06:14

在下多于一对一还好控制,对于一对多和多对多方面配置经常出错,作个代码备份,代码地址:http://www.itneng.com/thread-3693-1-1.html

标签:Hibernate

[1].[文件] HibernateOneToManyBidirectional.part1.rar ~ 4MB    下载(11) 跳至 [1] [2] [3]

文件不存在或者代码语言不存在

[2].[文件] HibernateOneToManyBidirectional.part2.rar ~ 334KB    下载(10) 跳至 [1] [2] [3]

文件不存在或者代码语言不存在

[3].[代码] [Java]代码 跳至 [1] [2] [3]

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
importjava.io.Serializable;
importjava.util.*;
 
importorg.hibernate.*;
importorg.hibernate.cfg.*;
importorg.hibernate.criterion.*;
importorg.hibernate.event.*;
importorg.hibernate.event.def.*;
 
publicclass Main {
   publicstatic void main(String[] args) throwsException {
      HibernateUtil.setup("create table grouptable (id int,name varchar);");   
      HibernateUtil.setup("create table story (id int,info varchar,idx int,parent_id int);");   
 
      Session session = HibernateUtil.currentSession();
 
      Group sp = newGroup("Group Name");
 
 
      HashSet set = newHashSet();
      Story s = newStory("A Story");
      s.setParent(sp);
      set.add(s);
      sp.setStories(set);
 
      Transaction transaction = null;
 
      try{
           transaction = session.beginTransaction();
           session.save(sp);
           transaction.commit();
      }catch(Exception e) {
           if(transaction != null) {
             transaction.rollback();
             throwe;
           }
      finally{
           session.close();
      }
      HibernateUtil.checkData("select * from grouptable");
      HibernateUtil.checkData("select * from story");     
   }
}
 
 
 
 
/////////////////////////////////////////////////////////////////////////
 
importjava.util.*;
 
publicclass Group {
  privateint id;
  privateString name;
  privateSet stories;
 
  publicGroup(){
  }
 
  publicGroup(String name) {
    this.name = name;
  }
 
  publicvoid setId(inti) {
    id = i;
  }
 
  publicint getId() {
    returnid;
  }
 
  publicvoid setName(String n) {
    name = n;
  }
 
  publicString getName() {
    returnname;
  }
 
  publicvoid setStories(Set l) {
    stories = l;
  }
 
  publicSet getStories() {
    returnstories;
  }
}
 
 
 
/////////////////////////////////////////////////////////////////////////
importjava.util.*;
 
publicclass Story {
  privateint id;
  privateString info;
  privateGroup parent;
 
  publicvoid setParent(Group g) {
    parent = g;
  }
  publicGroup getParent() {
    returnparent;
  }
  publicStory(){
  }
 
  publicStory(String info) {
    this.info = info;
  }
 
  publicvoid setId(inti) {
    id = i;
  }
 
  publicint getId() {
    returnid;
  }
 
  publicvoid setInfo(String n) {
    info = n;
  }
 
  publicString getInfo() {
    returninfo;
  }
}
 
 
 
/////////////////////////////////////////////////////////////////////////
 
 
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
    PUBLIC"-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
 
<hibernate-mapping>
    <classname="Group"table="grouptable">
        <id name="id"unsaved-value="0">
             <generatorclass="increment"/>
        </id>
 
        <set name="stories"cascade="all"inverse="true">
             <key column="parent_id"/>
             <one-to-manyclass="Story"/>
        </set>
        <property name="name"type="string"/>
    </class>
 
    <classname="Story"table="story">
        <id name="id"unsaved-value="0">
             <generatorclass="increment"/>
        </id>
        <property name="info"/>
        <many-to-one name="parent"column="parent_id"not-null="true"/>
    </class>
</hibernate-mapping>
 
 
/////////////////////////////////////////////////////////////////////////
<?xml version='1.0'encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
        <property name="connection.url">jdbc:hsqldb:data/tutorial</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>
 
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
 
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
 
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
 
        <!-- Mapping files -->
        <mapping resource="Group.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
 
 
 
/////////////////////////////////////////////////////////////////////////
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.Statement;
 
importjava.sql.ResultSet;
importjava.sql.ResultSetMetaData;
 
importorg.hibernate.HibernateException;
importorg.hibernate.Session;
importorg.hibernate.SessionFactory;
importorg.hibernate.cfg.Configuration;
 
publicclass HibernateUtil {
 
    publicstatic final SessionFactory sessionFactory;
 
    static{
        try{
            // Create the SessionFactory from hibernate.cfg.xml
            sessionFactory = newConfiguration().configure().buildSessionFactory();
        }catch(Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            thrownew ExceptionInInitializerError(ex);
        }
    }
 
    publicstatic final ThreadLocal session = newThreadLocal();
 
    publicstatic Session currentSession() throwsHibernateException {
        Session s = (Session) session.get();
        // 如果本来没有,打开一个新的Session
        if(s == null) {
            s = sessionFactory.openSession();
            // 保存
            session.set(s);
        }
        returns;
    }
 
    publicstatic void closeSession() throwsHibernateException {
        Session s = (Session) session.get();
        if(s != null)
            s.close();
        session.set(null);
    }
 
    staticConnection conn;
    staticStatement st;
  publicstatic void setup(String sql) {
    try{
      // 加载 JDBC 驱动.
      Class.forName("org.hsqldb.jdbcDriver");
      System.out.println("Driver Loaded.");
      //建立到数据库的连接
      String url = "jdbc:hsqldb:data/tutorial";
 
      conn = DriverManager.getConnection(url, "sa","");
      System.out.println("Got Connection.");
 
      st = conn.createStatement();
      st.executeUpdate(sql);
    }catch(Exception e) {
      System.err.println("Got an exception! ");
      e.printStackTrace();
      System.exit(0);
    }
  }
  publicstatic void checkData(String sql) {
    try{
      HibernateUtil.outputResultSet(st
          .executeQuery(sql));
//      conn.close();
    }catch(Exception e) {
      e.printStackTrace();
    }
  }
 
    publicstatic void outputResultSet(ResultSet rs) throwsException{
    ResultSetMetaData metadata = rs.getMetaData();
 
    intnumcols = metadata.getColumnCount();
    String[] labels = newString[numcols];
    int[] colwidths = newint[numcols];
    int[] colpos = newint[numcols];
    intlinewidth;
 
      for(inti = 0; i < numcols; i++) {
        labels[i] = metadata.getColumnLabel(i + 1);
        System.out.print(labels[i]+"  ");
    }
      System.out.println("------------------------");
 
    while(rs.next()) {
        for(inti = 0; i < numcols; i++) {
        Object value = rs.getObject(i + 1);
        if(value == null){
            System.out.print("       ");
        }else{
            System.out.print(value.toString().trim()+"   ");
        }
 
      }
        System.out.println("       ");
    }
    }
}

0 0