[Hibernate] - many to one
Hibernate的多对一操作:
例子参考引用:
http://www.tutorialspoint.com/hibernate/hibernate_many_to_one_mapping.htm
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://127.0.0.1/testdb</property>
<property name="connection.username">root</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.MySQL5Dialect</property> <!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property> <!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property> <mapping resource="com/my/hbm/User.hbm.xml"/>
<mapping resource="com/my/hbm/UserAccount.hbm.xml"/> </session-factory> </hibernate-configuration>
User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping> <class name="com.my.bean.User" table="user">
<id name="id" type="int">
<column name="id" />
<generator class="native" />
</id>
<property name="name" type="java.lang.String" length="50">
<column name="name" not-null="true" length="50" />
</property>
<property name="age" type="int">
<column name="age" />
</property>
<property name="password" type="java.lang.String" length="50">
<column name="password" length="50" />
</property>
<property name="email" type="java.lang.String" length="100">
<column name="email" length="100" />
</property>
<property name="createtime" type="java.util.Date">
<column name="createtime" />
</property>
</class> </hibernate-mapping>
UserAccount.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping> <class name="com.my.bean.UserAccount" table="user_account">
<id name="id" type="int">
<column name="id" />
<generator class="native" />
</id>
<many-to-one name="user" column="user_id" class="com.my.bean.User" not-null="true"></many-to-one>
<property name="account" type="java.lang.String" length="50">
<column name="account" not-null="true" length="50" />
</property>
</class> </hibernate-mapping>
Java Bean: User.java
package com.my.bean; import java.util.Date; public class User {
private int id;
private String name;
private int age;
private String password;
private String email;
private Date createtime; public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
}
Java Bean: UserAccount.java
package com.my.bean; public class UserAccount { private int id;
private String account;
private User user; public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
} }
HibernateUtil.java
package com.my.dao.util; import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
return configuration.configure().buildSessionFactory(
new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build());
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
} public static SessionFactory getSessionFactory() {
return sessionFactory;
} }
测试:
package com.my.init; import java.util.Date;
import java.util.List; import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session; import com.my.bean.User;
import com.my.bean.UserAccount;
import com.my.dao.util.HibernateUtil; public class Test { public static void main(String[] args) {
Test t = new Test(); // Add new user
User user = t
.addUser("robin", "abcd1234", "robin@88db.com", new Date());
System.out.println(user.getId()); // Get user list
List<User> users = t.listUser();
for (User item : users) {
System.out.println("User name: " + item.getName());
} // Add UserAccount
UserAccount ua = t.addUserAccount("robinzhang", user);
System.out.println("Add UserAccount: " + ua.getId()); // Update UserAccount
UserAccount ua_u = t.updateUserAccount(ua.getId(), "robin_zhang");
System.out.println("Update UserAccount: " + ua_u.getAccount()); // Get User Account List
List<UserAccount> uas = t.listUserAccount();
for (UserAccount item : uas) {
System.out.println("UserAccount: " + item.getAccount());
System.out.println("UserID: " + item.getUser().getId());
} // Delete UserAccount
boolean result = t.deleteUserAccount(1);
System.out.println("Delete UserAccount: " + result); // Delete User
result = t.deleteUser(user);
System.out.println("Delete User: " + result);
} /**
* List Users
*/
@SuppressWarnings("unchecked")
public List<User> listUser() {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction(); List<User> users = null;
try {
// Select action
String hqlSelect = "from User where name like :name";
Query query = session.createQuery(hqlSelect);
query.setParameter("name", "%ro%");
users = query.list();
session.getTransaction().commit();
} catch (HibernateException e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
}
return users;
} /**
* Add new user
*
* @param name
* User name
* @param password
* User password
* @param email
* User email
* @param createtime
* User create time
* @return User object
*/
public User addUser(String name, String password, String email,
Date createtime) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction(); User u = new User();
try {
u.setName(name);
u.setPassword(password);
u.setCreatetime(createtime);
u.setEmail(email);
u.setAge(18);
// Get new user id
Integer userid = (Integer) session.save(u);
session.getTransaction().commit();
} catch (HibernateException e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
} return u;
} /**
* Get UserAccount Object
*
* @param account
* account name
* @param user
* User ID
* @return UserAccount object
*/
public UserAccount addUserAccount(String account, User user) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction(); UserAccount ua = null;
try {
ua = new UserAccount();
ua.setAccount(account);
ua.setUser(user);
session.save(ua);
session.getTransaction().commit();
} catch (HibernateException e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
} return ua;
} /**
* Get User Account List
*
* @return
*/
@SuppressWarnings("unchecked")
public List<UserAccount> listUserAccount() {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction(); List<UserAccount> uas = null;
try {
String hqlSelect = "from UserAccount where account like :account";
Query query = session.createQuery(hqlSelect);
query.setParameter("account", "%ro%");
uas = query.list();
session.getTransaction().commit();
} catch (HibernateException e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
} return uas;
} /**
* Update User Account
*
* @param id
* @param account
*/
public UserAccount updateUserAccount(Integer id, String account) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction(); UserAccount ua = null;
try {
ua = (UserAccount) session.get(UserAccount.class, id);
ua.setAccount(account);
session.update(ua);
session.getTransaction().commit();
} catch (HibernateException e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
} return ua;
} /**
* Delete UserAccount
*
* @param id
* @return true/false
*/
public boolean deleteUserAccount(Integer id) {
boolean result = false;
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction(); try {
UserAccount ua = (UserAccount) session.get(UserAccount.class, id);
session.delete(ua);
session.getTransaction().commit();
result = true;
} catch (HibernateException e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
} return result;
} /**
* Delete User
*
* @param user
* @return
*/
public boolean deleteUser(User user) {
boolean result = false;
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction(); try {
session.delete(user);
session.getTransaction().commit();
result = true;
} catch (HibernateException e) {
if (session.getTransaction() != null)
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
} return result;
} }
使用Hibernate会自动建库。
[Hibernate] - many to one的更多相关文章
- hibernate多对多关联映射
关联是类(类的实例)之间的关系,表示有意义和值得关注的连接. 本系列将介绍Hibernate中主要的几种关联映射 Hibernate一对一主键单向关联Hibernate一对一主键双向关联Hiberna ...
- 解决 Springboot Unable to build Hibernate SessionFactory @Column命名不起作用
问题: Springboot启动报错: Caused by: org.springframework.beans.factory.BeanCreationException: Error creati ...
- hibernate多对一双向关联
关联是类(类的实例)之间的关系,表示有意义和值得关注的连接. 本系列将介绍Hibernate中主要的几种关联映射 Hibernate一对一主键单向关联Hibernate一对一主键双向关联Hiberna ...
- Hibernate中事务的隔离级别设置
Hibernate中事务的隔离级别,如下方法分别为1/2/4/8. 在Hibernate配置文件中设置,设置代码如下
- Hibernate中事务声明
Hibernate中JDBC事务声明,在Hibernate配置文件中加入如下代码,不做声明Hibernate默认就是JDBC事务. 一个JDBC 不能跨越多个数据库. Hibernate中JTA事务声 ...
- spring applicationContext.xml和hibernate.cfg.xml设置
applicationContext.xml配置 <?xml version="1.0" encoding="UTF-8"?> <beans ...
- [原创]关于Hibernate中的级联操作以及懒加载
Hibernate: 级联操作 一.简单的介绍 cascade和inverse (Employee – Department) Casade用来说明当对主对象进行某种操作时是否对其关联的从对象也作类似 ...
- hibernate的基本xml文件配置
需要导入基本的包hibernate下的bin下的required和同bin下optional里的c3p0包下的所有jar文件,当然要导入mysql的驱动包了.下面需要注意的是hibernate的版本就 ...
- Maven搭建SpringMVC+Hibernate项目详解 【转】
前言 今天复习一下SpringMVC+Hibernate的搭建,本来想着将Spring-Security权限控制框架也映入其中的,但是发现内容太多了,Spring-Security的就留在下一篇吧,这 ...
- 1.Hibernate简介
1.框架简介: 定义:基于java语言开发的一套ORM框架: 优点:a.方便开发; b.大大减少代码量; c.性能稍高(不能与数据库高手相比,较一般数据库使用者 ...
随机推荐
- LeetCode Subsets II (DFS)
题意: 给一个集合,有n个可能相同的元素,求出所有的子集(包括空集,但是不能重复). 思路: 看这个就差不多了.LEETCODE SUBSETS (DFS) class Solution { publ ...
- LeetCode Longest Increasing Subsequence (LIS O(nlogn))
题意: 给一个数组,求严格递增的最长递增子序列的长度. 思路: 开销是一个额外的O(n)的数组.lower_bound(begin,end,val)的功能是:返回第一个大于等于val的地址. clas ...
- 【题解】【数组】【Leetcode】Merge Sorted Array
Given two sorted integer arrays A and B, merge B into A as one sorted array. Note: You may assume th ...
- mac自带apache服务器开启
mac的os x操作系统自带的有apach服务器, 命令行: sudo apachectl -v 可查看自带apache版本信息 输入: sudo apachectl start 就开启了apa ...
- Cache
1.Cache中的块与主存储器中的块时按照什么样的规则建立对应关系的? 2.在这种对应关系下,主存地址又是如何变换成Cache地址的? Cache信息: 1.数据Cache和指令Cache是分开还是统 ...
- Ubuntu 13.10下Hadoop 2.2 安装、配置、编译(伪分布式)
1.安装JDK.在此不做解说,上篇博文里已介绍过.http://www.cnblogs.com/lifeinsmile/p/3578677.html 2.配置ssh. ssh服务,用于管理远程Hado ...
- css link和@import区别
1.link语法结构 <link href="CSSurl路径" rel="stylesheet" type="text/css" / ...
- socket 简介
对TCP/IP.UDP.Socket编程这些词你不会很陌生吧?随着网络技术的发展,这些词充斥着我们的耳朵.那么我想问: 1. 什么是TCP/IP.UDP?2. Sock ...
- T语言TC发布脚本方法
代码模式的注册码发布脚本方法 注册码项目模式的发布脚本方法 1.注册码项目发布版 2.注册码项目代理版 这两种方法都是基于注册码项目来实现的,所以在使用之前,需要先创建注册码项目.
- linux文件系统---10
进入 Linux 根目录(即“/”, Linux 文件系统的入口, 也是处于最高一级的目录),运行“ls –l”命令,可以看到 Linux 系统包含以下目录. 1./bin 包含基本命令,如 ls.c ...