本例子中有两个类一个用户类,一个应用类,多个应用对应一个用户。
应用类
@Entity
public class AppManager {
private String app;
private String appName;
private String appPwd;
private int id;
private UserManager userManager;
@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="username")
public UserManager getUserManager() {
return userManager;
}
public void setUserManager(UserManager userManager) {
this.userManager = userManager;
}
public String getApp() {
return app;
}
public String getAppName() {
return appName;
}
public String getAppPwd() {
return appPwd;
}
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setApp(String app) {
this.app = app;
}
public void setAppName(String appName) {
this.appName = appName;
}
public void setAppPwd(String appPwd) {
this.appPwd = appPwd;
}
public void setId(int id) {
this.id = id;
}
}
用户类
@Entity
public class UserManager {
@Id
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpwd() {
return userpwd;
}
public void setUserpwd(String userpwd) {
this.userpwd = userpwd;
}
private String username;
private String userpwd;
}
测试类
@Test
public void query() {
Session session = sif.getCurrentSession();
session.beginTransaction();
Query query= session.createQuery("from AppManager app,UserManager user where app.userManager = user.username ");
List list =query.list();
session.getTransaction().commit();
JSONArray jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray.toString());
Iterator iter = list.iterator();
while(iter.hasNext()){
Object[] object = (Object[])iter.next();
JSONArray jsonArray1 = JSONArray.fromObject(object);
System.out.println(jsonArray1.toString());
AppManager a1 = (AppManager)object[0];
JSONArray jsonArray2 = JSONArray.fromObject(a1);
System.out.println(jsonArray2.toString());
UserManager u1 = (UserManager)object[1];
System.out.println(a1.getApp());
System.out.println(u1.getUsername());
}
}
结果为
Hibernate:
select
appmanager0_.id as id0_0_, //个人猜测:Object[0],Object[1]这里的0和1对应
usermanage1_.username as username1_1_,
appmanager0_.app as app0_0_,
appmanager0_.appName as appName0_0_,
appmanager0_.appPwd as appPwd0_0_,
appmanager0_.username as username0_0_,
usermanage1_.userpwd as userpwd1_1_
from
AppManager appmanager0_,
UserManager usermanage1_
where
appmanager0_.username=usermanage1_.username // UserManager类转成外键username,引用类型作为外键与基本类型做为的主键能对应上。
[[{"app":"sina","appName":"123","appPwd":"2123","id":303,"userManager":{"username":"jym","userpwd":""}},{"username":"jym","userpwd":""}]]
[{"app":"sina","appName":"123","appPwd":"2123","id":303,"userManager":{"username":"jym","userpwd":""}},{"username":"jym","userpwd":""}]
[{"app":"sina","appName":"123","appPwd":"2123","id":303,"userManager":{"username":"jym","userpwd":""}}]
sina
jym
以JSON的格式输出可以看出,hibernate返回的外键值付给了AppManager类的UserManager引用的username属性。
在把List链表里的值转成Object数组时不是杂乱无章的,而是按照两个类分别付给了Object。