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的更多相关文章

  1. hibernate多对多关联映射

    关联是类(类的实例)之间的关系,表示有意义和值得关注的连接. 本系列将介绍Hibernate中主要的几种关联映射 Hibernate一对一主键单向关联Hibernate一对一主键双向关联Hiberna ...

  2. 解决 Springboot Unable to build Hibernate SessionFactory @Column命名不起作用

    问题: Springboot启动报错: Caused by: org.springframework.beans.factory.BeanCreationException: Error creati ...

  3. hibernate多对一双向关联

    关联是类(类的实例)之间的关系,表示有意义和值得关注的连接. 本系列将介绍Hibernate中主要的几种关联映射 Hibernate一对一主键单向关联Hibernate一对一主键双向关联Hiberna ...

  4. Hibernate中事务的隔离级别设置

    Hibernate中事务的隔离级别,如下方法分别为1/2/4/8. 在Hibernate配置文件中设置,设置代码如下

  5. Hibernate中事务声明

    Hibernate中JDBC事务声明,在Hibernate配置文件中加入如下代码,不做声明Hibernate默认就是JDBC事务. 一个JDBC 不能跨越多个数据库. Hibernate中JTA事务声 ...

  6. spring applicationContext.xml和hibernate.cfg.xml设置

    applicationContext.xml配置 <?xml version="1.0" encoding="UTF-8"?> <beans ...

  7. [原创]关于Hibernate中的级联操作以及懒加载

    Hibernate: 级联操作 一.简单的介绍 cascade和inverse (Employee – Department) Casade用来说明当对主对象进行某种操作时是否对其关联的从对象也作类似 ...

  8. hibernate的基本xml文件配置

    需要导入基本的包hibernate下的bin下的required和同bin下optional里的c3p0包下的所有jar文件,当然要导入mysql的驱动包了.下面需要注意的是hibernate的版本就 ...

  9. Maven搭建SpringMVC+Hibernate项目详解 【转】

    前言 今天复习一下SpringMVC+Hibernate的搭建,本来想着将Spring-Security权限控制框架也映入其中的,但是发现内容太多了,Spring-Security的就留在下一篇吧,这 ...

  10. 1.Hibernate简介

    1.框架简介: 定义:基于java语言开发的一套ORM框架: 优点:a.方便开发;           b.大大减少代码量;           c.性能稍高(不能与数据库高手相比,较一般数据库使用者 ...

随机推荐

  1. Linux关机命令

    1.halt  :关机 init 0 : 关机 shutdown  -h  now (立刻关机)  -h 指的是  halt 2.reboot  重启 init 0 重启 shutdown -r no ...

  2. Linux Shell 命令

    (1) 操作一个文件并对文件查询行进行切分处理 (或者1-) (2) 操作文件进行去重并显示重复次数 | sort | uniq -c (3) 查看总的汇总行数 | sort | uniq -c | ...

  3. Examining Open vSwitch Traffic Patterns

    In this post, I want to provide some additional insight on how the use of Open vSwitch (OVS) affects ...

  4. IE8 CSS hack 测试

    IE8正式版出来有一段日子了,但是针对ie8正式版的CSS hack却很少,其实这是值得庆幸的,因为ie8修复了很多IE6和IE7的一些BUG,更加接近W3C标准.针对IE8正式版的CSS hack目 ...

  5. 能不能对metronic继续封装一下呢

    按照这篇文章的说法,目前metronic的层级还是较低的,只是针对Bootstrap做了很多的用例(最佳实践). 我上一个项目是用easy UI,准确地说,是经过简单封装的easy UI.用起来非常爽 ...

  6. 2016-2017 ACM-ICPC, NEERC, Southern Subregional Contest (Online Mirror, ACM-ICPC Rules, Teams Preferred) G 优先队列

    G. Car Repair Shop time limit per test 2 seconds memory limit per test 512 megabytes input standard ...

  7. Hive 复习

    hive分为CLI(command line)(用的比较多) JDBC/ODBC-ThriftServer hiveServer(hive -service hiveserver),JDBC访问,一个 ...

  8. 用类求圆面积c++

    #include<iostream>.#include<math.h>using namespace std;class Circle{    public:        d ...

  9. 使用jquery插件实现图片延迟加载技术(懒加载)

    有时我们看到一些大型网站,页面如果有很多图片的时候,当你滚动到相应的行时,当前行的图片才即时加载的,这样子的话页面在打开只加可视区域的图片,而其它隐藏的图片则不加载,一定程序上加快了页面加载的速度,对 ...

  10. 编码规范(一)之Code Templates的设置(转)

    编码规范(一)之Code Templates的设置 基于公司的主流开发工具为eclipse,但每个人都有自己的编码习惯,为了统一格式,这里通过三个方面:设置Code Templates.Checkst ...