RSS

OneToOne Bidirectional & Unidirectional Association

15 Mar

OneToOne Bidirectional Association

Person MySQL

NAME TYPE NULLABLE KEY EXTRA
id int(11) NO PRI auto_increment
name varchar(20) NO    
age int(11) YES    
phone varchar(15) YES    
address varchar(50) YES    
cardid varchar(18) YES MUL  

Card MySQL

NAME TYPE NULLABLE KEY EXTRA
cid varchar(18) NO PRI  
varDate date YES    

persistence.xml

<?xml version=“1.0” encoding=“UTF-8”?>

<persistence version=“2.0”

xmlns=http://java.sun.com/xml/ns/persistence&#8221; xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance&#8221;

xsi:schemaLocation=http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd>

<persistence-unit name=“ejb3” transaction-type=“JTA”>

<provider>org.hibernate.ejb.HibernatePersistence</provider>

<jta-data-source>java:/DefaultMySqlDS</jta-data-source>

<class>com.xavier.ejb3.entitybean.Person</class>

<class>com.xavier.ejb3.entitybean.Card</class>       

<properties>

<property name=“hibernate.show_sql” value=“true” />

<property name=“hibernate.format_sql” value=“true” />

<property name=“hibernate.dialect” value=“org.hibernate.dialect.MySQLDialect” />

</properties>

</persistence-unit>

</persistence>

 

Person.java

package com.xavier.ejb3.entitybean;

import java.io.Serializable;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.OneToOne;

import javax.persistence.Table;

import static javax.persistence.CascadeType.PERSIST;

import static javax.persistence.CascadeType.REMOVE;

 

@Entity

@Table(name=“person”)

@SuppressWarnings(“serial”)

public class Person implements Serializable{

private int id;

private String name;

private int age;

private String phone;

private String address;

private Card card;

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

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 getPhone() {

return phone;

}

public void setPhone(String phone) {

this.phone = phone;

}

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

@OneToOne(optional = true, cascade = { PERSIST, REMOVE })

@JoinColumn(name = “cardid”, referencedColumnName = “cid”, nullable=true)

public Card getCard() {

return card;

}

public void setCard(Card card) {

this.card = card;

}

}

 

Card.java

package com.xavier.ejb3.entitybean;

import java.io.Serializable;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.OneToOne;

import javax.persistence.Table;

import static javax.persistence.CascadeType.MERGE;

 

@Entity

@Table(name=“card”)

@SuppressWarnings(“serial”)

public class Card implements Serializable{

private String cid;

private String varDate;

private Person person;

@Id

public String getCid() {

return cid;

}

public void setCid(String cid) {

this.cid = cid;

}

@Column(nullable=true)

public String getVarDate() {

return varDate;

}

public void setVarDate(String varDate) {

this.varDate = varDate;

}

@OneToOne(optional = true, cascade = { MERGE }, mappedBy = “card”, orphanRemoval = false)

public Person getPerson() {

return person;

}

public void setPerson(Person person) {

this.person = person;

}

}

 

PersonLocal.java

package com.xavier.ejb3.sessionbean;

import com.xavier.ejb3.entitybean.Person;

 

public interface PersonLocal {

public void addPerson(String name, int age, String phone, String address, String cid, String varDate);

public Person getPersonByCid(String cid);

public void updatePerson(Person pp,String cid);

}

 

Personbean.java

package com.xavier.ejb3.sessionbean;

import com.xavier.ejb3.entitybean.Card;

import com.xavier.ejb3.entitybean.Person;

import javax.ejb.Local;

import javax.ejb.Stateless;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

import javax.persistence.Query;

 

@Stateless

@Local(PersonLocal.class)

public class Personbean implements PersonLocal {

@PersistenceContext(unitName=“ejb3”)

protected EntityManager em;

    public void addPerson(String name, int age, String phone, String address, String cid, String varDate) {

        Person p = new Person();

        Card c = new Card();

        c.setCid(cid);

        c.setVarDate(varDate);

//     c.setPerson(p);

        p.setName(name);

        p.setAge(age);

        p.setPhone(phone);

        p.setAddress(address);

        p.setCard(c);

        em.persist(p);

    }

 

    public void updatePerson(Person pp, String cid) {

        Person p = this.getPersonByCid(cid);

//        p.setName(pp.getName());

//        p.setAge(pp.getAge());

//        p.setPhone(pp.getPhone());

//        p.setAddress(pp.getAddress());

        p.getCard().setVarDate(pp.getCard().getVarDate());

    }

 

    public Person getPersonByCid(String cid) {

        Query q = em.createQuery(“select p from Person p where p.card.cid = :cid”);

        q.setParameter(“cid”, cid);

        Person p = (Person)q.getSingleResult();

        return p;

    }

 

}

 

CardLocal.java

package com.xavier.ejb3.sessionbean;

import com.xavier.ejb3.entitybean.Card;

 

public interface CardLocal {

public void delCard(String cid);

public Card getCardByCid(String cid);

public void delCardByJPQL(String cid);

}

 

Cardbean.java

package com.xavier.ejb3.sessionbean;

import com.xavier.ejb3.entitybean.Card;

import com.xavier.ejb3.entitybean.Person;

import javax.ejb.Local;

import javax.ejb.Stateless;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

import javax.persistence.Query;

 

@Stateless

@Local(CardLocal.class)

public class Cardbean implements CardLocal {

@PersistenceContext(unitName=“ejb3”)

protected EntityManager em;

    public void delCard(String cid) {

        em.remove(em.find(Card.class, cid));

    }

   

    public void delCardByJPQL(String cid){

        Person person = (Person)em.createQuery(“select p from Person p where p.card.cid = :cid”).setParameter(“cid”, cid).getSingleResult();

        person.setCard(null);

        em.flush();

        Query query = em.createQuery(“delete from Card c where c.cid = :cid”);

        query.setParameter(“cid”, cid);

        query.executeUpdate();

       

    }

 

    public Card getCardByCid(String cid) {

return em.find(Card.class, cid);

    }

 

}

 

OneToOne1Test.jsp

<%@ page language=“java” contentType=“text/html; charset=UTF-8”

pageEncoding=“UTF-8”%>

<%@ page

import=“javax.naming.*,com.xavier.ejb3.sessionbean.*,com.xavier.ejb3.entitybean.*,java.util.*”%>

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” http://www.w3.org/TR/html4/loose.dtd>

<html>

<head>

<meta http-equiv=“Content-Type” content=“text/html; charset=UTF-8”>

<title>One To One Testing</title>

</head>

<body>

<%

try {

final Hashtable jndiProperties = new Hashtable();

jndiProperties.put(Context.PROVIDER_URL, “localhost:1099”);

jndiProperties.put(Context.URL_PKG_PREFIXES,

“org.jboss.ejb.client.naming”);

//jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, “org.jnp.interfaces.NamingContextFactory”);

Context ctx = new InitialContext(jndiProperties);

PersonLocal pl = (PersonLocal) ctx

.lookup(“ejb:ejb3/ejb3//Personbean!com.xavier.ejb3.sessionbean.PersonLocal”);

//Add Person

pl.addPerson(“Xavier”, 29, “13400000000”, “Dalian”,

“21021021002102210”, “2012-04-24”);

//Get Person

Person p = (Person) pl.getPersonByCid(“21021021002102210”);

out.println(“<br>————–After adding person——————“);

out.println(“<br>Name: “ + p.getName());

out.println(“<br>Age: “ + p.getAge());

out.println(“<br>Phone: “ + p.getPhone());

out.println(“<br>Address: “ + p.getAddress());

out.println(“<br>Identity: “ + p.getCard().getCid());

out.println(“<br>Valide Date: “ + p.getCard().getVarDate());

//Update Person

Person pp = new Person();

pp = pl.getPersonByCid(“21021021002102210”);

pp.getCard().setVarDate(“2012-12-12”);

pl.updatePerson(pp, “21021021002102210”);

out.println(“<br>————After updating person info————–“);

//Get Updated Person Info

Person p1 = (Person) pl.getPersonByCid(“21021021002102210”);

out.println(“<br>————–After adding person——————“);

out.println(“<br>Name: “ + p1.getName());

out.println(“<br>Age: “ + p1.getAge());

out.println(“<br>Phone: “ + p1.getPhone());

out.println(“<br>Address: “ + p1.getAddress());

out.println(“<br>Identity: “ + p1.getCard().getCid());

out.println(“<br>Valide Date: “ + p1.getCard().getVarDate());

} catch (Exception e) {

out.println(e.getMessage());

}

%>

</body>

</html>

 

OneToOne2Test.jsp

<%@ page language=“java” contentType=“text/html; charset=UTF-8”

pageEncoding=“UTF-8”%>

<%@ page

import=“javax.naming.*, com.xavier.ejb3.sessionbean.*, com.xavier.ejb3.entitybean.*, java.util.*”%>

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” http://www.w3.org/TR/html4/loose.dtd>

<html>

<head>

<meta http-equiv=“Content-Type” content=“text/html; charset=UTF-8”>

<title>One To One Testing</title>

</head>

<body>

<%

try{

final Hashtable jndiProperties = new Hashtable();

jndiProperties.put(Context.PROVIDER_URL, “localhost:1099”);

jndiProperties.put(Context.URL_PKG_PREFIXES, “org.jboss.ejb.client.naming”);

//jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, “org.jnp.interfaces.NamingContextFactory”);

Context ctx = new InitialContext(jndiProperties);

CardLocal cl = (CardLocal) ctx.lookup(“ejb:ejb3/ejb3//Cardbean!com.xavier.ejb3.sessionbean.CardLocal”);

//Get Card

Card card = cl.getCardByCid(“21021021002102210”);

//Get Person

                           /*out.println(“<br>Name: ” + card.getPerson().getName());

out.println(“<br>Age: ” + card.getPerson().getAge());

out.println(“<br>Phone: ” + card.getPerson().getPhone());

out.println(“<br>Address: ” + card.getPerson().getAddress());

out.println(“<br>Identity: ” + card.getPerson().getCard().getCid());

out.println(“<br>Valide Date: ” + card.getPerson().getCard().getVarDate()); */

//Delete Card

//cl.delCard(“21021021002102210”);

cl.delCardByJPQL(“21021021002102210”);

out.println(“Card is deleted!”);

}catch(Exception e){

out.println(e.getMessage());

}

%>

</body>

</html>

Note: mappedBy is placed to the referenced table (which doesn’t have foreign key). @JoinColumn is placed in main table (which has foreign key).

 

OneToOne Unidirectional Association

Remove Card.java @OneToOne annotation and Person property.

Advertisements
 
Leave a comment

Posted by on 03/15/2012 in EJB

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: