`
hunter090730
  • 浏览: 194739 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

@OneToMany与@ManyToMany

    博客分类:
  • SSH
 
阅读更多
==========User.java=========
package com.me.model;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "T_USER", schema = "SSHE")
public class User implements java.io.Serializable {

// Fields
private String id;
private String name;
private String pwd;
private Date createdatetime;
private Date modifydatetime;
private Set<Address> addresses = new HashSet<Address>();
private Set<Role> roles = new HashSet<Role>();

// Constructors

/** default constructor */
public User() {
}

/** minimal constructor */
public User(String id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}

/** full constructor */
public User(String id, String name, String pwd, Date createdatetime,
Date modifydatetime) {
this.id = id;
this.name = name;
this.pwd = pwd;
this.createdatetime = createdatetime;
this.modifydatetime = modifydatetime;
}

// Property accessors
@Id
@Column(name = "ID", unique = true, nullable = false, length = 36)
public String getId() {
return this.id;
}

public void setId(String id) {
this.id = id;
}

@Column(name = "NAME", nullable = false, length = 100)
public String getName() {
return this.name;
}

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

@Column(name = "PWD", nullable = false, length = 32)
public String getPwd() {
return this.pwd;
}

public void setPwd(String pwd) {
this.pwd = pwd;
}

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "CREATEDATETIME", length = 7)
public Date getCreatedatetime() {
return this.createdatetime;
}

public void setCreatedatetime(Date createdatetime) {
this.createdatetime = createdatetime;
}

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "MODIFYDATETIME", length = 7)
public Date getModifydatetime() {
return this.modifydatetime;
}

public void setModifydatetime(Date modifydatetime) {
this.modifydatetime = modifydatetime;
}

@OneToMany(cascade = CascadeType.ALL, mappedBy = "contactName", fetch = FetchType.EAGER)
public Set<Address> getAddresses() {
return addresses;
}

public void setAddresses(Set<Address> addresses) {
this.addresses = addresses;
}

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "USER_ROLE", joinColumns = { @JoinColumn(name = "USER_ID",referencedColumnName = "id")}, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
public Set<Role> getRoles() {
return roles;
}

public void setRoles(Set<Role> roles) {
this.roles = roles;
}

}


=====================Role.java

package com.me.model;

import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name = "T_ROLE", schema = "SSHE")
public class Role implements java.io.Serializable {
private int id;

private String role;

private Set<User> users;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getRole() {
return role;
}

public void setRole(String role) {
this.role = role;
}

// @ManyToMany(fetch = FetchType.LAZY, mappedBy = "students")

@ManyToMany(fetch = FetchType.LAZY,mappedBy = "roles")
public Set<User> getUsers() {
return users;
}

public void setUsers(Set<User> users) {
this.users = users;
}
}

====================Address.java================
package com.me.model;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "T_ADDRESS", schema = "SSHE")
public class Address implements java.io.Serializable {
private User contactName;
private String postCode;
private String detail;
private String phone;
private Integer id;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

@ManyToOne(cascade = { CascadeType.ALL })
@JoinColumn(name = "USER_ID")
public User getContactName() {
return contactName;
}

public void setContactName(User contactName) {
this.contactName = contactName;
}

@Column(name = "CODE", length = 50)
public String getPostCode() {
return postCode;
}

public void setPostCode(String postCode) {
this.postCode = postCode;
}

@Column(name = "DETAIL", length = 200)
public String getDetail() {
return detail;
}

public void setDetail(String detail) {
this.detail = detail;
}

@Column(name = "PHONE_NUM", length = 200)
public String getPhone() {
return phone;
}

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

}


===================UserServiceImpl.java=============
package me.gacl.service.impl;


import java.io.Serializable;
import java.util.List;

import me.gacl.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.me.dao.UserDao;
import com.me.model.User;
//使用Spring提供的@Service注解将UserServiceImpl标注为一个Service
@Service("userService")
public class UserServiceImpl implements UserService {
  /**
     * 注入userDao
     */
    @Autowired
    private UserDao userDao;
   
    public void test() {
        System.out.println("Hello World!");
    }

    public Serializable save(User user) {
        return userDao.save(user);
    }

public List<User> getUsers() {
return userDao.getUsers();
}


}
===================UserDaoImpl.java==================

package com.me.dao.impl;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.me.dao.UserDao;
import com.me.model.User;

@Repository("userDao")
public class UserDaoImpl implements UserDao {
   
    /**
     * 使用@Autowired注解将sessionFactory注入到UserDaoImpl中
     */
    @Resource
    private SessionFactory sessionFactory;
   
    public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

public Serializable save(User user) {
        return sessionFactory.getCurrentSession().save(user);
    }

public List<User> getUsers() {
Session session= sessionFactory.openSession();
return session.createQuery("from User").list();

}
}

=================TestHiberante.java==================
package com.me.test;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import me.gacl.service.UserService;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.me.model.Address;
import com.me.model.Role;
import com.me.model.User;

public class TestHibernate {

    private UserService userService;
   
    /**
     * 这个before方法在所有的测试方法之前执行,并且只执行一次
     * 所有做Junit单元测试时一些初始化工作可以在这个方法里面进行
     * 比如在before方法里面初始化ApplicationContext和userService
     */
    @Before
    public void before(){
        ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-hibernate.xml"});
        userService = (UserService) ac.getBean("userService");
    }
   
    @Test
    public void testSaveMethod(){
        //ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-hibernate.xml"});
        //UserServiceI userService = (UserServiceI) ac.getBean("userService");
        User user = new User();
        user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        user.setName("gacl");
        user.setPwd("123");
        user.setCreatedatetime(new Date());
        userService.save(user);
    }
    @Test
    public void testFindMethod(){
        //ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-hibernate.xml"});
        //UserServiceI userService = (UserServiceI) ac.getBean("userService");
     
        List<User> list=userService.getUsers();
        System.out.println(list.size());
    }
    @Test
    public void testOtMSaveMethod(){
        //ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-hibernate.xml"});
        //UserServiceI userService = (UserServiceI) ac.getBean("userService");
        User user = new User();
        user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        user.setName("gacl");
        user.setPwd("123");
        user.setCreatedatetime(new Date());
        Address a=new Address();
        a.setContactName(user);
        a.setDetail("Sz xxx");
        a.setPhone("18956264598");
        a.setPostCode("898989");
        Address ab=new Address();
        ab.setContactName(user);
        ab.setDetail("Sz xxx12");
        ab.setPhone("18956264598");
        ab.setPostCode("888989");
        user.getAddresses().add(ab);
        user.getAddresses().add(a);
        userService.save(user);
    }
    @Test
    public void testGetsMethod(){
        //ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-hibernate.xml"});
        //UserServiceI userService = (UserServiceI) ac.getBean("userService");
     
        List<User> list=userService.getUsers();
        for (User user : list) {
        System.out.println(user.getName());
        Set<Address> set=user.getAddresses();
        for (Address address : set) {
System.out.println(address.getPhone());
}
}
    }
    @Test
    public void testMTM(){
    User user = new User();
         user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
         user.setName("comMe");
         user.setPwd("123");
         user.setCreatedatetime(new Date());
         Role r=new Role();
         r.setRole("Adminstrator");
         Role r1=new Role();
         r1.setRole("Hr");
         user.getRoles().add(r1);
         user.getRoles().add(r);
         userService.save(user);
    }
}
分享到:
评论
1 楼 hunter090730 2018-04-24  
最近在研究如何提高网站排名,以http://www.hbszlcc.com/为名,有兴趣的朋友一起来探讨啊

相关推荐

    hibernate对象三状态及OneToOne&OneToMany&ManyToMany

    本篇将详细阐述Hibernate中的对象三状态、一对一(OneToOne)、一对多(OneToMany)以及多对多(ManyToMany)关系映射。 一、Hibernate对象三状态 1. 游离态(Detached):对象在应用程序中创建,但尚未与Session...

    JPA课程manyToMany OneToMany 等全部测试

    `@OneToMany`注解表示一个实体可以与另一个实体的一组实例相关联,即一对多的关系。例如,一个部门有多个员工。在JPA中,我们可以这样设置: ```java @Entity public class Department { @OneToMany(mappedBy = ...

    Hibernate关于注解的一对多,多对多,一对一

    1. **@ManyToMany** 注解:在两个实体类中都需要使用此注解,分别表示各自实体与其他实体的关系。 2. **@JoinTable**:多对多关系通常需要一个中间表来存储双方的关联,`@JoinTable`用来定义这个中间表,包括它的...

    hibernate多对多及一对多的案例

    同时,在多方类中,对应的外键字段上使用`@ManyToOne`注解,表明它与另一方的关联。配置包括以下几点: 1. 在一方实体类中,定义集合属性,并添加`@OneToMany`注解,指定关联的多方类、外键字段和级联操作等。 ```...

    hibernate 一对多 多对多

    在Hibernate中,我们可以通过在映射文件或注解中设置`@OneToMany`来定义这种关系。这个注解通常放在父类(“一”端)的属性上,同时需要指定子类(“多”端)的主键作为外键。例如: ```java @Entity public class ...

    jpa的实体映射关系7种

    在Java Persistence API (JPA) 中,实体映射关系是数据库关系模型与Java对象模型之间的桥梁,用于在ORM(对象关系映射)框架下管理数据。JPA 提供了多种映射关系,使得开发者能够方便地处理不同类型的关联。下面我们...

    Android数据库框架-----ORMLite关联表的使用

    在ORMLite中,我们可以利用`@OneToOne`、`@OneToMany`、`@ManyToOne`和`@ManyToMany`注解来处理这些关联。这些注解分别表示一对一、一对多、多对一和多对多的关系。 1. **一对一关联**(@OneToOne):一个实体类...

    Hibernate 关联映射

    这通常通过在多方实体上声明`@ManyToOne`,并在一方向上声明`@OneToMany`来实现。`mappedBy`属性用于指定由哪个实体管理关联。例如,一个部门可以有多个员工: ```java @Entity public class Department { @Id ...

    hibernate关联映射详解SSH 多对多,一对多关系对象映射

    在数据库中,一对多关系意味着一个表中的记录可以与另一个表中的多个记录相关联。在Hibernate中,这可以通过在实体类中使用`@OneToMany`注解来实现。该注解定义了一个实体可以拥有多个其他实体的实例。例如,一个...

    hibernate的多种映射关系

    通过 `mappedBy` 参数在 `@OneToMany` 或 `@ManyToMany` 注解中,可以指定关系的维护方,从而简化代码并提高效率。 9. **联合主键 (Composite Key)** 当一个表的主键由两个或更多列组成时,需要使用联合主键。在 ...

    eclipselink-plugins-nosql-4.0.2.v20230613-3bfa6ac6dd.zip

    EclipseLink,开源的持久化框架,是Eclipse Foundation的一部分,它Eclipse...此外,EclipseLink还提供了一套丰富的实体映射规范,如@OneToOne、@OneToMany、@ManyToOne和@ManyToMany等注解,以支持SQL和NOSQL数据库。

    CH4Hibernate2,一对多,多对一,多对多实现增删改查

    Hibernate作为Java领域中最流行的ORM(对象关系映射)框架,能够简化数据库操作,将SQL语句与Java代码分离,提高开发效率。接下来,我们将深入探讨这些关系类型以及如何在实际项目中应用它们。 一、一对多关系(One...

    hibernate注解处理映射关系共14页.pdf.zip

    5. @ManyToMany:用于处理多对多关系,需要一个中间表来保存两个实体的关联关系。@JoinTable注解用来定义这个中间表,包括表名、连接两个实体的外键列名。 6. @Inheritance和@Inheritance(strategy=InheritanceType...

    Hibernate Annotations Reference 中文参考手册HTML版

    4. **关系映射**:Hibernate 支持多种关系映射,包括一对一(@OneToOne)、一对多(@OneToMany)、多对一(@ManyToOne)和多对多(@ManyToMany)。例如,用户与角色的关系: ```java @ManyToOne @JoinColumn(name...

    hibernate表关联实例

    多对一关联是与一对多关联相对应的,即多个实体可以关联到一个实体。例如,多个订单可以关联到一个客户。定义如下: ```java @Entity public class Order { @Id @GeneratedValue(strategy = GenerationType....

    jpa-开发21

    一对多关联是指一个实体可以与多个其他实体相联系,而多个实体只能与一个实体相联系。在 JPA 中,这种关系可以通过 `@OneToMany` 和 `@ManyToOne` 注解来实现。 1.1.1 多对一 在一对多关系中,通常规定多的一方...

    hibernate关联关系

    Hibernate是Java领域中一款流行的持久化框架,它简化了数据库操作,通过ORM(对象关系映射)技术将Java对象与数据库中的记录对应起来。在Hibernate中,关联关系是指Java对象之间的关系如何映射到数据库表之间的关系...

    hibernate关联映射

    其中,关联映射是Hibernate的核心特性之一,它允许我们将对象模型与关系数据库模型之间的关系进行清晰的定义。本文将深入探讨Hibernate中的关联映射,包括一对一、一对多、多对一和多对多四种关联类型。 ### 1. 一...

    hibernate映射图

    在IT行业中,Hibernate是一个强大的Java持久化框架,它简化了数据库操作,使开发人员能够将对象模型与数据库结构关联起来。"hibernate映射图"是描述这种关联的工具,它通过XML或注解的形式定义了数据模型与数据库表...

Global site tag (gtag.js) - Google Analytics