Hibernate关联查询


项目框架数据库表

Hibernate关联查询_第1张图片Hibernate关联查询_第2张图片Hibernate关联查询_第3张图片Hibernate关联查询_第4张图片

分析:两个表之间的关联查询需要两个工具类,两个工具类对应两个映射文件,这也是hibernate的缺点,几个工具类就需要对应多少工具类
同时还需要将两个类互相注入也就是user要注入到phone中,phone也需要注入到user中
同时在这其中如出现错误大部分是映射文件配置出错,需要注意映射文件的名称,需要的属性。

代码块
User.java
package dao;
import java.sql.Date;

public class User {
private String idcard;
private String name;
private String password;
private String age;
private String addr;
Phone phone;

public Phone getPhone() {
return phone;
}

public void setPhone(Phone phone) {
this.phone = phone;
}

public User() {
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getIdcard() {
return idcard;
}

public void setIdcard(String idcard) {
this.idcard = idcard;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAge() {
return age;
}

public void setAge(String age) {
this.age = age;
}

public String getAddr() {
return addr;
}

public void setAddr(String addr) {
this.addr = addr;
}
}

User.hbm.xml
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

Phone.java
package dao;

public class Phone {
String idcard;
String phone;
User user;

public String getIdcard() {
return idcard;
}

public void setIdcard(String idcard) {
this.idcard = idcard;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}
}

Phone.hbm.xml
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
insert="false" update="false" not-null="true" />

hibernate.cfg.xml
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
com.mysql.jdbc.Driver
jdbc:mysql:///zdy?useUnicode=true&characterEncoding=UTF8
root
root
org.hibernate.dialect.MySQL5Dialect
true
true
update

Test.java
package dao;

import java.sql.Date;
import java.util.*;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Test {
public static void main(String[] args) {
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hql = "FROM User u,Phone t WHERE u.idcard=t.idcard ";
Query query = session.createQuery(hql);
List list = query.list();
System.out.println(list.toString());
//
tx.commit();
session.close();
// sessionFactory.close();// 一定 不 要 关闭.这里只是写出来做例子
}
}

你可能感兴趣的:(java_hibernate)