`
zisefeiniao
  • 浏览: 174343 次
  • 性别: Icon_minigender_2
  • 来自: 成都
社区版块
存档分类
最新评论

EJB实体Bean开发的一对多关系映射

阅读更多

六、EJB实体Bean开发的一对多关系映射

1、在JBoss中配置数据源

方法见四、EJB实体Bean开发

并且保证JBoss中有该数据库连接jar包,例如:

2、建立项目

 

 

 

 

 

 

3、在persitence.xml中配置数据源连接

配置完成后会在EJB端项目中创建一个META-INF/persitence.xml文件,在该文件中进行连接等配置

(1)配置数据源

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="http://java.sun.com/xml/ns/persistence"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence

    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">

   

    <persistence-unit name="mysql" transaction-type="JTA">

        <jta-data-source>java:jdbc/mysql</jta-data-source>

    </persistence-unit>

 

</persistence>

(2)打开show_sql

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="http://java.sun.com/xml/ns/persistence"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence

    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">

   

    <persistence-unit name="mysql" transaction-type="JTA">

        <jta-data-source>java:jdbc/mysql</jta-data-source>

        <properties>

           <property name="hibernate.show_sql" value="true"/>

        </properties>

    </persistence-unit>

 

</persistence>

 

4、生成EntityBean映射

DROP TABLE person ;

DROP TABLE groups ;

 

CREATE TABLE groups (

    id                int               primary key auto_increment ,

    title             varchar(20)          not null ,

    description          text              not null

);

 

CREATE TABLE person (

    uid               varchar(18)          primary key ,

    name              varchar(20)          not null,

    age               int               not null,

    gid               int               not null,

    foreign key (gid) references groups (id) on delete cascade

);

 

 

 

 

package org.mldn.lin.entity;

 

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.FetchType;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.ManyToOne;

import javax.persistence.Table;

 

@Entity

@Table(name = "person", catalog = "testdb", uniqueConstraints = {})

public class Person implements java.io.Serializable {

    private String uid;

 

    private Groups groups;

 

    private String name;

 

    private Integer age;

 

    public Person() {

    }

 

    public Person(String uid, Groups groups, String name, Integer age) {

       this.uid = uid;

       this.groups = groups;

       this.name = name;

       this.age = age;

    }

 

    @Id

    @Column(name = "uid", unique = true, nullable = false, insertable = true, updatable = true, length = 18)

    public String getUid() {

       return this.uid;

    }

 

    public void setUid(String uid) {

       this.uid = uid;

    }

 

    // 表示该类与Groups类有多对一关系

    // cascade表示级联关系,是否同时进行操作,与hibernate中的cascade相同,如果不写任何内容表示none值,如果填写可以从CascadeType的enum中选择适合的方式

    // fetch表示加载方式,如果值为LAZY表示使用延迟加载,如果为EAGER表示不使用

    @ManyToOne(cascade = {}, fetch = FetchType.LAZY)

    // 表示关系字段的映射配置

    @JoinColumn(name = "gid", unique = false, nullable = false, insertable = true, updatable = true)

    public Groups getGroups() {

       return this.groups;

    }

 

    public void setGroups(Groups groups) {

       this.groups = groups;

    }

 

    @Column(name = "name", unique = false, nullable = false, insertable = true, updatable = true, length = 20)

    public String getName() {

       return this.name;

    }

 

    public void setName(String name) {

       this.name = name;

    }

 

    @Column(name = "age", unique = false, nullable = false, insertable = true, updatable = true)

    public Integer getAge() {

       return this.age;

    }

 

    public void setAge(Integer age) {

       this.age = age;

    }

 

}

package org.mldn.lin.entity;

 

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.OneToMany;

import javax.persistence.Table;

 

@Entity

@Table(name = "groups", catalog = "testdb", uniqueConstraints = {})

public class Groups implements java.io.Serializable {

 

    private Integer id;

 

    private String title;

 

    private String description;

 

    private Set<Person> persons = new HashSet<Person>(0);

 

    public Groups() {

    }

 

    public Groups(Integer id, String title, String description) {

       this.id = id;

       this.title = title;

       this.description = description;

    }

 

    public Groups(Integer id, String title, String description,

           Set<Person> persons) {

       this.id = id;

       this.title = title;

       this.description = description;

       this.persons = persons;

    }

 

    @Id

//自增长

    @GeneratedValue

    @Column(name = "id", unique = true, nullable = false, insertable = true, updatable = true)

    public Integer getId() {

       return this.id;

    }

 

    public void setId(Integer id) {

       this.id = id;

    }

 

    @Column(name = "title", unique = false, nullable = false, insertable = true, updatable = true, length = 20)

    public String getTitle() {

       return this.title;

    }

 

    public void setTitle(String title) {

       this.title = title;

    }

 

    @Column(name = "description", unique = false, nullable = false, insertable = true, updatable = true, length = 65535)

    public String getDescription() {

       return this.description;

    }

 

    public void setDescription(String description) {

       this.description = description;

    }

    //表示该类与Person包含一对多关系,在对方对象中也包含一个对应的属性叫groups

    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY, mappedBy = "groups")

    public Set<Person> getPersons() {

       return this.persons;

    }

 

    public void setPersons(Set<Person> persons) {

       this.persons = persons;

    }

 

}

 

5、新建SessionBean操作EntityBean

srcànewàEJB3 SessionBean

 

package org.mldn.lin.session;

 

import javax.ejb.Remote;

 

import org.mldn.lin.entity.Person;

 

@Remote

public interface PersonDAORemote {

    public boolean doCreate(Person person)throws Exception;

    public Person findById(String uid)throws Exception;

}

 

package org.mldn.lin.session;

 

import javax.ejb.Stateless;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

 

import org.mldn.lin.entity.Person;

 

@Stateless

public class PersonDAO implements PersonDAORemote {

 

    @PersistenceContext

    private EntityManager em;

    public boolean doCreate(Person person) throws Exception {

       // TODO Auto-generated method stub

       this.em.persist(person);

       return true;

    }

 

    public Person findById(String uid) throws Exception {

       // TODO Auto-generated method stub

       Person person=this.em.find(Person.class, uid);

       return person;

    }

   

}

 

package org.mldn.lin.session;

 

import javax.ejb.Remote;

 

import org.mldn.lin.entity.Groups;

 

@Remote

public interface GroupsDAORemote {

    public boolean doCreate(Groups groups)throws Exception;

    public Groups findById(int gid)throws Exception;

}

 

package org.mldn.lin.session;

 

import javax.ejb.Stateless;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

 

import org.mldn.lin.entity.Groups;

 

@Stateless

public class GroupsDAO implements GroupsDAORemote {

   

    @PersistenceContext

    private EntityManager em;

   

    public boolean doCreate(Groups groups) throws Exception {

       // TODO Auto-generated method stub

       this.em.persist(groups);

       return true;

    }

 

    public Groups findById(int gid) throws Exception {

       // TODO Auto-generated method stub

       Groups groups=this.em.find(Groups.class, gid);

       return groups;

    }

 

}

 

6、EJB端项目发布

 

7、在Web端建立测试类测试

通过测试类进行测试,需要将 拷贝到lib下即可

package org.mldn.lin.test;

 

import java.util.Properties;

 

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.naming.NamingException;

 

import org.mldn.lin.entity.Groups;

import org.mldn.lin.session.GroupsDAORemote;

import org.mldn.lin.session.PersonDAORemote;

 

public class Test {

 

    public static void main(String[] args) {

       // 定义查找参数,通过定义这些参数找到该公共空间

       Properties pro = new Properties();

        pro.setProperty("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");

       pro.setProperty("java.naming.provider.url", "192.168.1.187:1099");

       pro.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");

       // 通过JNDI查找发布的接口

       try {

           Context ctx = new InitialContext(pro);

 

           // 开始查找接口

           GroupsDAORemote gdao=(GroupsDAORemote) ctx.lookup("GroupsDAO/remote");

          

           Groups groups=new Groups();

           groups.setTitle("111");

          

           // 打印结果

           System.out.println(gdao.doCreate(groups));

 

       } catch (NamingException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       } catch (Exception e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

 

    }

 

}

 

8、处理jar包

此处采用测试类测试,而且因为有映射关系,所以会出现缺少支持类的错误,因此这里需要将用到的Hibernate3支持包拷贝到web端的lib下

对应的再查找所有需要用到的支持包,都包含以下内容:

, ,

在JBoss的D:\jboss-4.2.0.GA\server\default\lib目录下可以找到这些jar包,如果对于映射关系还不满足,那么可以在原来的SSH项目中找到完整版的Hibernate3的支持jar包来代替

 

9、处理Lazy

package org.mldn.lin.test;

 

import java.util.Properties;

 

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.naming.NamingException;

 

import org.mldn.lin.entity.Groups;

import org.mldn.lin.entity.Person;

import org.mldn.lin.session.GroupsDAORemote;

import org.mldn.lin.session.PersonDAORemote;

 

public class Test {

 

    public static void main(String[] args) {

       // 定义查找参数,通过定义这些参数找到该公共空间

       Properties pro = new Properties();

        pro.setProperty("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");

       pro.setProperty("java.naming.provider.url", "192.168.1.187:1099");

       pro.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");

       // 通过JNDI查找发布的接口

       try {

           Context ctx = new InitialContext(pro);

 

           // 开始查找接口

           GroupsDAORemote gdao=(GroupsDAORemote) ctx.lookup("GroupsDAO/remote");

           PersonDAORemote pdao=(PersonDAORemote) ctx.lookup("PersonDAO/remote");

          

           Groups groups=new Groups();

           groups.setTitle("111");

           groups.setDescription("第一组");

          

          

          

           Person person=new Person();

           person.setUid("lin");

           person.setName("mldn");

           person.setAge(25);

           Groups g=new Groups();

           g.setId(1);

           person.setGroups(g);

          

           Person person1=new Person();

           person1.setUid("wei");

           person1.setName("mldn");

           person1.setAge(25);

           person1.setGroups(g);

          

           // 打印结果

//         System.out.println(gdao.doCreate(groups));

//         System.out.println(gdao.findById(1).getTitle());

//         System.out.println(pdao.doCreate(person));

//         System.out.println(pdao.doCreate(person1));

//         System.out.println(pdao.findById("lin"));

           System.out.println(pdao.findById("lin").getGroups().getTitle());

          

           //System.out.println(gdao.findById(1).getPersons().size());

          

 

       } catch (NamingException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       } catch (Exception e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

 

    }

 

}

 

当进行级联查询时,不管通过一查多,还是通过多的查一,都会报lazy

严重: could not initialize proxy - no Session

org.hibernate.LazyInitializationException: could not initialize proxy - no Session

    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:57)

 

解决方案:

可以将LAZY关闭或在实现类中使用.的方式先进行查询

package org.mldn.lin.session;

 

import javax.ejb.Stateless;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

 

import org.mldn.lin.entity.Groups;

 

@Stateless

public class GroupsDAO implements GroupsDAORemote {

   

    @PersistenceContext

    private EntityManager em;

   

    public boolean doCreate(Groups groups) throws Exception {

       // TODO Auto-generated method stub

       this.em.persist(groups);

       return true;

    }

 

    public Groups findById(int gid) throws Exception {

       // TODO Auto-generated method stub

       Groups groups=this.em.find(Groups.class, gid);

       groups.getPersons().size();

       return groups;

    }

 

}

 

package org.mldn.lin.session;

 

import javax.ejb.Stateless;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

 

import org.mldn.lin.entity.Person;

 

@Stateless

public class PersonDAO implements PersonDAORemote {

 

    @PersistenceContext

    private EntityManager em;

    public boolean doCreate(Person person) throws Exception {

       // TODO Auto-generated method stub

       this.em.persist(person);

       return true;

    }

 

    public Person findById(String uid) throws Exception {

       // TODO Auto-generated method stub

       Person person=this.em.find(Person.class, uid);

       person.getGroups().getTitle();

       return person;

    }

   

}

 

分享到:
评论

相关推荐

    Jboss下开发ejb应用之一实体bean的应用

    如果需要处理一对一、一对多或多对多的关系,可以使用`@OneToOne`、`@OneToMany`、`@ManyToOne`或`@ManyToMany`注解。 在EJB项目中,还需要定义一个本地接口(Local Interface),它是客户端与实体Bean交互的接口,...

    Bean开发实例之三实体Bean开发实例

    **建立关系**:实体Bean还可以建立与其他实体Bean的关系,比如一对多或多对多的关系。这种关系可以通过实体Bean中的属性来表示,并通过相应的get/set方法进行操作。 #### 通过会话Bean访问实体Bean **会话Bean**是...

    EJB3开发Entity

    EJB3支持一对多(@OneToMany)、多对一(@ManyToOne)、一对一(@OneToOne)和多对多(@ManyToMany)的关系映射,通过注解来定义实体之间的关联。 9. **懒加载和即时加载** EJB3支持懒加载和即时加载策略,控制...

    ejb3 第10讲 --开发单表映射的实体bean

    使用`@OneToMany`或`@ManyToOne`注解可以定义一对多或多对一关系。默认情况下,关联的对象是懒加载的,只有在实际访问时才会加载。`CascadeType`可以设置级联操作,比如删除一个实体时,是否同时删除关联的实体。 ...

    JPA学习源码(EJB实体Bean)

    - **jpa_03.rar**:可能涉及实体关系映射,如一对一、一对多、多对一和多对多的关系,以及如何使用`@OneToOne`、`@OneToMany`、`@ManyToOne`和`@ManyToMany`注解。 - **jpa_04.rar**:可能涵盖实体管理器的使用,...

    JPA 批注参考 EJB3.0实体Bean注解详细解析

    ### Java Persistence API (JPA) 与 EJB 3.0 实体 Bean 注解详解 #### 一、JPA 概述与实体 Bean 的转变 Java Persistence API (JPA) 是 Java 社区规范 JSR-220 的一部分,旨在提供一种标准的方式来处理对象与关系...

    10_开发单表映射的实体bean

    在实际应用中,我们还可以利用`@OneToMany`、`@ManyToOne`、`@OneToOne`、`@ManyToMany`等注解来处理多对一、一对多、一对一和多对多的关系映射。这使得实体Bean能够更好地反映现实世界的业务模型。 开发实体Bean时...

    Myeclipse+JBoss开发的EJB3.0 一对多程序

    **EJB3.0简介** EJB(Enterprise JavaBeans)...通过MyEclipse和JBoss这样的工具,开发者可以更高效地构建和测试EJB3.0应用,而“一对多”的关系映射则是Java EE开发中的常见场景,它有助于更好地管理和组织业务数据。

    EJB2.0 Entity bean(PDF)

    **企业级JavaBeans(EJB)2.0实体Bean**是Java平台中用于构建可部署在企业级服务器上的分布式、事务处理和持久性应用程序的重要组件。这个PDF文档,"EJB2.0 Entity bean",可能包含了关于如何设计、实现和使用EJB2.0...

    浪曦_EJB3.0实例教程_多对多映射

    综上所述,EJB 3.0的多对多映射提供了灵活且易于配置的方式处理复杂的实体关系,使得Java EE开发者能够更加专注于业务逻辑,而不是底层的数据库操作。在实际开发中,应结合具体需求,合理设计和优化多对多映射,以...

    EJB2.0 Entity bean(PDF) .zip_EJB2 enti_EJB2.0 P_ejb_ejb2 CMP sup

    **企业级JavaBeans (EJB) 2.0 实体Bean详解** EJB(Enterprise JavaBeans)是Java EE(Enterprise Edition)平台的核心组件之一,它为构建可部署在服务器端的分布式应用程序提供了一种框架。EJB 2.0是EJB规范的一个...

    2022年EJB3.0开发之多对多和一对一Java教程.docx

    本文档主要关注的是多对多(ManyToMany)和一对一(OneToOne)关系的实现,这两种关系在Java编程和企业级JavaBean(EJB)中非常常见。 首先,多对多关系在现实生活中有很多实例,如学生和老师的关系。一个学生可以...

    EJB3.0开发Session Bean

    EJB 3.0是EJB规范的一个重大改进,极大地简化了开发过程,降低了对开发者的技术要求,使得更多开发者能够轻松地利用EJB进行企业级应用的开发。 **1. Session Beans概述** Session Beans是EJB中的一种类型,它们代表...

    EJB测试题。pdf

    关于M:N关系的映射问题,这通常涉及到如何在数据库中表示多对多的关系。实体之间的关系映射是ORM技术中的重要部分,它允许开发者通过对象而非数据库表来操作数据。 EJB3.0引入了注释(Annotations)的概念,它提供...

    EJB详解 sessionbean entitybean MDB

    在JPA中,可以通过注解来定义对象与数据库表的映射关系。 5. **安全性**: EJB支持角色基础的访问控制(RBAC),允许开发者定义不同级别的权限,确保只有授权的用户或角色才能访问特定的EJB服务。 6. **事务管理*...

    EJB简介Enterprise Java Bean 下载

    3. 实体Bean(Entity Bean):映射到持久化数据,如数据库记录,提供对数据的CRUD操作。 总结来说,EJB是J2EE平台的核心组件,它在多层架构中扮演着关键角色,通过容器提供的服务和JNDI接口,实现了高效、可扩展...

    基于EJB组件的分布式应用开发

    - **实体Bean**:实体Bean代表持久化的业务对象,通常映射到数据库表。它们可以是容器管理的持久性(CMP)或Bean管理的持久性(BMP)。CMP是由EJB容器自动处理实体Bean的持久化,而BMP则需要开发者自己编写代码来...

    容器管理实体EJB.rar

    这个实例可能涉及一个具体的EJB实体bean的实现,它展示了如何利用容器管理事务、持久化和生命周期。可能包括创建一个代表数据库表的bean类,定义相应的接口,设置JPA注解,编写部署描述符,并展示如何在客户端进行...

Global site tag (gtag.js) - Google Analytics