RSS

Generalized and UTC time

There are different notations used to designate date and time-related information. For example, the fourth day of February in the year 1999 can be written as:

2/4/99

4/2/99

99/2/4

4.2.1999

04-FEB-1999

 

as well as many other notations.

 

Directory Server standardizes the timestamp representation by requiring the LDAP servers to support two syntaxes:

  • The Generalized Time syntax, which takes the form:

YYYYMMDDHHMMSS[.|,fraction][(+|-HHMM)|Z]

There are 4 digits for the year, 2 digits each for the month, day, hour, minute, and second, and an optional fraction of a second. Without any further additions, a date and time is assumed to be in a local time zone. To indicate that a time is measured in Coordinated Universal Time, append a capital letter Z to a time or a local time differential. For example:

19991106210627.3

which in local time is 6 minutes, 27.3 seconds after 9 p.m. on 6 November 1999.

19991106210627.3Z

which is the coordinated universal time.

19991106210627.3-0500

which is local time as in the first example, with a 5 hour difference in relation to the coordinated universal time.

 

If you designate an optional fraction of a second, a period or a comma is required. For local time differential, a ‘+’ or a ‘-‘ must precede the hour-minute value

  • The Universal time syntax, which takes the form:

YYMMDDHHMM[SS][(+ | -)HHMM)|Z]

There are 2 digits each for the year, month, day, hour, minute, and optional second fields. As in GeneralizedTime, an optional time differential can be specified. For example, if local time is a.m. on 2 January 1999 and the coordinated universal time is 12 noon on 2 January 1999, the value of UTCTime is either:

“9901021200Z”

     or

“9901020700-0500”

If the local time is a.m. on 2 January 2001 and the coordinated universal time is 12 noon on 2 January 2001, the value of UTCTime is either:

“0101021200Z”

     or

“0101020700-0500”

UTCTime allows only 2 digits for the year value, therefore the usage is not recommended.

 

The supported matching rules are generalizedTimeMatch for equality and generalizedTimeOrderingMatch for inequality. Substring search is not allowed. For example, the following filters are valid:

 generalized-timestamp-attribute=199910061030

 utc-timestamp-attribute>=991006

 generalized-timestamp-attribute=*

 

The following filters are not valid:

generalized-timestamp-attribute=1999*

utc-timestamp-attribute>=*1010

 
Leave a comment

Posted by on 07/05/2012 in LDAP

 

EJB3 Message Driven Bean

Queue Message (Jboss AS7.1)

queue.jsp (Message Producer)

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

pageEncoding=“UTF-8”%>

<%@ page import=“javax.naming.*,java.text.*,javax.jms.*,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>Queue Message</title>

</head>

<body>

<%

QueueConnection conn = null;

QueueSession session1 = null;

try {

//Set Properties of JNDI

final Properties jndiProperties = new Properties();

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.jboss.naming.remote.client.InitialContextFactory”);

Context ctx = new InitialContext(jndiProperties);

 

//QueueConnectionFactory, QueueConnection, QueueSession

QueueConnectionFactory factory = (QueueConnectionFactory) ctx

.lookup(“java:/ConnectionFactory”);

conn = factory.createQueueConnection();

session1 = conn.createQueueSession(false,

QueueSession.AUTO_ACKNOWLEDGE);

 

//QueueConnection Starts

conn.start();

//Retrieve Destination

Destination destination = (javax.jms.Queue) ctx

.lookup(“queue/test”);

out.println(“Send the following info to Message Driven Bean: <br>”);

 

//Create Message Producer

MessageProducer producer = session1.createProducer(destination);

 

//Send Text

TextMessage msg = session1

.createTextMessage(“This is my first Message Driven Bean”);

//out.println(“This is my first Message Driven Bean”);

producer.send(msg);

 

//Send Map Message

MapMessage mapmsg = session1.createMapMessage();

mapmsg.setObject(“No.1”, “Dalian”);

//out.println(“Dalian<br>”);

producer.send(mapmsg);

 

//Send BytesMessage

BytesMessage bmsg = session1.createBytesMessage();

bmsg.writeBytes(“This is BytesMessage”.getBytes());

//out.println(“This is BytesMessage”);

producer.send(bmsg);

 

//Send StreamMessage

StreamMessage smsg = session1.createStreamMessage();

smsg.writeString(“May Day”);

producer.send(smsg);

 

out.println(“All messages are sent, please check JBoss Console<br>”);

 

} catch (Exception e) {

out.println(e.getMessage());

} finally {

try {

session1.close();

conn.close();

} catch (JMSException e) {

e.printStackTrace();

}

}

%>

</body>

</html>

 

Messager.java (Message Consumer)

package com.xavier.ejb3.messagedrivenbean;

import java.io.ByteArrayOutputStream;

import javax.ejb.ActivationConfigProperty;

import javax.ejb.MessageDriven;

import javax.jms.BytesMessage;

import javax.jms.MapMessage;

import javax.jms.Message;

import javax.jms.MessageListener;

import javax.jms.StreamMessage;

import javax.jms.TextMessage;

 

@MessageDriven(name = “MessagerMDB”, activationConfig = {

@ActivationConfigProperty(propertyName = “destinationType”, propertyValue = “javax.jms.Queue”),

@ActivationConfigProperty(propertyName = “destination”, propertyValue = “queue/test”) })

public class Messager implements MessageListener {

 

public void onMessage(Message msg) {

try {

if (msg instanceof TextMessage) {

TextMessage tmsg = (TextMessage) msg;

String content = tmsg.getText();

this.print(“Text: “+ content);

} else if (msg instanceof MapMessage) {

MapMessage map = (MapMessage) msg;

String content = (String) map.getString(“No.1”);

this.print(“Map Message: “+ content);

} else if (msg instanceof BytesMessage) {

BytesMessage bmsg = (BytesMessage) msg;

ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

byte[] buffer = new byte[256];

int length = 0;

while ((length = bmsg.readBytes(buffer)) != -1) {

byteStream.write(buffer, 0, length);

}

String content = new String(byteStream.toByteArray());

byteStream.close();

this.print(“BytesMessage: “+ content);

} else if (msg instanceof StreamMessage) {

StreamMessage smsg = (StreamMessage) msg;

String content =smsg.readString();

this.print(“StreamMessage: “+ content);

}

} catch (Exception e) {

e.printStackTrace();

}

}

 

private void print(String content) {

System.out.println(content);

}

 

}

 

Topic Message (Jboss AS7.1)

topic.jsp (Message Producer)

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

pageEncoding=“UTF-8”%>

<%@ page import=“javax.naming.*,java.text.*,javax.jms.*,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>Topic Message</title>

</head>

<body>

<%

TopicConnection conn = null;

TopicSession session1 = null;

try {

//Set Properties of JNDI

final Properties jndiProperties = new Properties();

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.jboss.naming.remote.client.InitialContextFactory”);

Context ctx = new InitialContext(jndiProperties);

 

//TopicConnectionFactory, TopicConnection, TopicSession

TopicConnectionFactory factory = (TopicConnectionFactory) ctx

.lookup(“java:/ConnectionFactory”);

conn = factory.createTopicConnection();

session1 = conn.createTopicSession(false,

TopicSession.AUTO_ACKNOWLEDGE);

 

//TopicConnection Starts

//conn.start();

//Retrieve Destination

Destination destination = (javax.jms.Topic) ctx

.lookup(“topic/test”);

out.println(“Send the following info to Message Driven Beans: <br>”);

 

//Create Message Producer

MessageProducer producer = session1.createProducer(destination);

 

//Send Text

TextMessage msg = session1

.createTextMessage(“This is my first Message Driven Bean”);

//out.println(“This is my first Message Driven Bean”);

producer.send(msg);

 

} catch (Exception e) {

out.println(e.getMessage());

} finally {

try {

session1.close();

conn.close();

} catch (JMSException e) {

e.printStackTrace();

}

}

%>

</body>

</html>

 

TopicPrintBean1 (Message Consumer)

package com.xavier.ejb3.messagedrivenbean;

import javax.ejb.ActivationConfigProperty;

import javax.ejb.MessageDriven;

import javax.jms.Message;

import javax.jms.MessageListener;

import javax.jms.TextMessage;

 

@MessageDriven(

activationConfig = {

@ActivationConfigProperty(propertyName = “destinationType”, propertyValue = “javax.jms.Topic”),

@ActivationConfigProperty(propertyName = “destination”, propertyValue=“topic/test”)

})

public class TopicPrintBean1 implements MessageListener {

 

    public void onMessage(Message message) {

       try{

           TextMessage tmsg = (TextMessage) message;

           String content = tmsg.getText();

           System.out.println(this.getClass().getName() + “==” + content);

       }catch(Exception e){

           e.printStackTrace();

       }

    }

 

}

 

TopicPrintBean2 (Message Consumer)

package com.xavier.ejb3.messagedrivenbean;

import javax.ejb.ActivationConfigProperty;

import javax.ejb.MessageDriven;

import javax.jms.Message;

import javax.jms.MessageListener;

import javax.jms.TextMessage;

 

@MessageDriven(

activationConfig = {

@ActivationConfigProperty(propertyName = “destinationType”, propertyValue = “javax.jms.Topic”),

@ActivationConfigProperty(propertyName = “destination”, propertyValue = “topic/test”),

})

public class TopicPrintBean2 implements MessageListener {

 

    public void onMessage(Message message) {

        try{

            TextMessage tmsg = (TextMessage)message;

            String content = tmsg.getText();

            System.out.println(this.getClass().getName() + “==” + content);

        }catch(Exception e){

            e.printStackTrace();

        }

    }

 

}

Note: Life Cycle Annotation of MDB are @PostConstruct and @PreDestroy.

 
Leave a comment

Posted by on 03/18/2012 in EJB

 

ManyToMany Association

ManyToMany Bidirectional Association

Teacher

NAME TYPE NULLABLE KEY EXTRA
tid int(11) NO PRI auto_increment
name varchar(20) NO    
techType varchar(20) YES    

Student

NAME TYPE NULLABLE KEY EXTRA
sid int(11) NO PRI auto_increment
name varchar(20) NO    

Teacher_Student

NAME TYPE NULLABLE KEY EXTRA
teacher_id int(11) NO PRI  
student_id int(11) NO PRI  

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.Teacher</class>

<class>com.xavier.ejb3.entitybean.Student</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>

 

Teacher.java

package com.xavier.ejb3.entitybean;

import java.io.Serializable;

import java.util.HashSet;

import java.util.Set;

import javax.persistence.CascadeType;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.ManyToMany;

import javax.persistence.Table;

import static javax.persistence.GenerationType.IDENTITY;

import static javax.persistence.FetchType.EAGER;

import javax.persistence.JoinTable;

import javax.persistence.JoinColumn;

 

@SuppressWarnings(“serial”)

@Entity

@Table(name = “teacher”)

public class Teacher implements Serializable {

private int tid;

private String name;

private String techType;

private Set<Student> students = new HashSet<Student>();

public Teacher(){

}

public Teacher(String name, String techType){

this.name = name;

this.techType = techType;

this.students = null;

}

 

@Id

@GeneratedValue(strategy = IDENTITY)

public int getTid() {

return tid;

}

 

public void setTid(int tid) {

this.tid = tid;

}

 

@Column(nullable = false)

public String getName() {

return name;

}

 

public void setName(String name) {

this.name = name;

}

 

@Column(nullable = false)

public String getTechType() {

return techType;

}

 

public void setTechType(String techType) {

this.techType = techType;

}

 

@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, fetch = EAGER)

@JoinTable(name = “teacher_student”,

joinColumns = @JoinColumn(name = “teacher_id”, referencedColumnName = “tid”), 

inverseJoinColumns = @JoinColumn(name = “student_id”, referencedColumnName = “sid”))

public Set<Student> getStudents() {

return students;

}

 

public void setStudents(Set<Student> students) {

this.students = students;

}

 

}

 

Student.java

package com.xavier.ejb3.entitybean;

import java.io.Serializable;

import java.util.HashSet;

import java.util.Set;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.ManyToMany;

import javax.persistence.Table;

import static javax.persistence.GenerationType.IDENTITY;

import static javax.persistence.CascadeType.ALL;

import static javax.persistence.FetchType.EAGER;

 

@SuppressWarnings(“serial”)

@Entity

@Table(name=“student”)

public class Student implements Serializable {

private int sid;

private String name;

private Set<Teacher> teachers = new HashSet<Teacher>();

public Student(){

}

public Student(String name){

this.name = name;

this.teachers = null;

}

@Id

@GeneratedValue(strategy = IDENTITY)

public int getSid() {

return sid;

}

public void setSid(int sid) {

this.sid = sid;

}

@Column(nullable=false)

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@ManyToMany(cascade = ALL, fetch = EAGER, mappedBy = “students”)

public Set<Teacher> getTeachers() {

return teachers;

}

public void setTeachers(Set<Teacher> teachers) {

this.teachers = teachers;

}

}

 

TeacherStudentLocal.java

package com.xavier.ejb3.sessionbean;

import java.util.Set;

import com.xavier.ejb3.entitybean.Student;

import com.xavier.ejb3.entitybean.Teacher;

 

public interface TeacherStudentLocal {

public void addTeacher(String name,String techType, Set<Student> students);

public Teacher getTeacherById(int tid);   

public void removeTeacher(int tid);

public void removeTeacherKeepStudent(int tid);

public void removeMiddleTable(int tid);

}

 

TeacherStudentBean.java

package com.xavier.ejb3.sessionbean;

import java.util.Set;

import com.xavier.ejb3.entitybean.Student;

import com.xavier.ejb3.entitybean.Teacher;

import javax.ejb.Local;

import javax.ejb.Stateless;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

import javax.persistence.Query;

 

@Stateless

@Local(TeacherStudentLocal.class)

public class TeacherStudentBean implements TeacherStudentLocal {

 

@PersistenceContext(name=“ejb3”)

protected EntityManager em;

    public void addTeacher(String name, String techType, Set<Student> students) {

       Teacher teacher = new Teacher(name, techType);

       teacher.setStudents(students);

       em.persist(teacher);

    }

 

    public Teacher getTeacherById(int tid) {

return em.find(Teacher.class, tid);

    }

 

    public void removeTeacher(int tid){

        em.remove(em.find(Teacher.class, tid));

    }

   

    public void removeTeacherKeepStudent(int tid){

        Teacher teacher = em.find(Teacher.class, tid);

        Set<Student> students = teacher.getStudents();

        for(Student student : students){

            student.setTeachers(null);

        }

        em.remove(teacher);

    }

   

    public void removeMiddleTable(int tid){

        Query query = em.createNativeQuery(“delete from teacher_student where teacher_id = :tid”);

        query.setParameter(“tid”, tid);

        query.executeUpdate();

    }

}

 

ManyToManyTest.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>Many To Many Test</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”);

//org.jboss.naming.remote.client.InitialContextFactory

Context ctx = new InitialContext(jndiProperties);

TeacherStudentLocal tsl = (TeacherStudentLocal) ctx

.lookup(“ejb:ejb3/ejb3//TeacherStudentBean!com.xavier.ejb3.sessionbean.TeacherStudentLocal”);

//Add Teacher

/*Set<Student> students = new HashSet<Student> ();

students.add(new Student(“Xavier”));

students.add(new Student(“Joe”));

students.add(new Student(“Javier”));

tsl.addTeacher(“Zoe”, “Math”, students);*/

//Get Teacher

/*Teacher t = tsl.getTeacherById(3);

out.println(“<br>———————Teacher Information————————-“);

out.println(“<br>Teacher Name: ” + t.getName());

out.println(“<br>Teaches: ” + t.getTechType());

out.println(“<br>All his/her students: “);

students.clear();

students = t.getStudents();

for(Student s: students){

out.println(s.getName() + “\t”);

}*/

 

//Delete Teacher and remove all her students.

//tsl.removeTeacher(4);

//tsl.removeTeacherKeepStudent(4);

tsl.removeMiddleTable(1);

 

} catch (Exception e) {

out.println(e.getMessage());

}

%>

</body>

</html>

 

ManyToMany Unidirectional Association

Remove Student.java @ManyToMany annotation and Set<Teacher> teachers property.

 
Leave a comment

Posted by on 03/17/2012 in EJB

 

OneToMany & ManyToOne Association

OneToMany & ManyToOne Bidirectional Association

Department MySQL

NAME TYPE NULLABLE KEY EXTRA
id int(11) NO PRI auto_increment
name varchar(20) NO    

Employee 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    
departmentid int(11) NO MUL  

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.Employee</class>

<class>com.xavier.ejb3.entitybean.Department</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>

 

Department.java

package com.xavier.ejb3.entitybean;

import java.io.Serializable;

import java.util.Set;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.OneToMany;

import javax.persistence.Table;

import static javax.persistence.CascadeType.MERGE;

import static javax.persistence.CascadeType.REMOVE;

import static javax.persistence.CascadeType.REFRESH;

import static javax.persistence.FetchType.EAGER;

 

@SuppressWarnings(“serial”)

@Entity

@Table(name=“department”)

public class Department implements Serializable{

private int id;

private String name;

private Set<Employee> employees;

@Id

@GeneratedValue(strategy=GenerationType.IDENTITY)

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

@Column(nullable=false)

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@OneToMany (cascade = { MERGE, REMOVE, REFRESH }, fetch = EAGER, mappedBy = “department”)

public Set<Employee> getEmployees() {

return employees;

}

public void setEmployees(Set<Employee> employees) {

this.employees = employees;

}

}

 

Employee.java

package com.xavier.ejb3.entitybean;

import java.io.Serializable;

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;

import static javax.persistence.CascadeType.MERGE;

import static javax.persistence.CascadeType.REFRESH;

 

@SuppressWarnings(“serial”)

@Entity

@Table(name=“employee”)

public class Employee implements Serializable {

private int id;

private String name;

private int age;

private String phone;

private Department department;

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

@Column(nullable=false)

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@Column(nullable=true)

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

@Column(nullable=true)

public String getPhone() {

return phone;

}

public void setPhone(String phone) {

this.phone = phone;

}

@ManyToOne(optional = false, cascade = { MERGE, REFRESH })

@JoinColumn(name=“departmentid”, referencedColumnName=“id”)

public Department getDepartment() {

return department;

}

public void setDepartment(Department department) {

this.department = department;

}

}

 

DepartmentLocal.java

package com.xavier.ejb3.sessionbean;

import com.xavier.ejb3.entitybean.Department;

 

public interface DepartmentLocal {

public Department getDepartmentById(int id);

public void delDepartment(int id);

}

 

DepartmentBean.java

package com.xavier.ejb3.sessionbean;

import com.xavier.ejb3.entitybean.Department;

import javax.ejb.Local;

import javax.ejb.Stateless;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

 

@Stateless

@Local(DepartmentLocal.class)

public class DepartmentBean implements DepartmentLocal {

@PersistenceContext(unitName=“ejb3”)

protected EntityManager em;

    public void delDepartment(int id) {

        em.remove(em.find(Department.class, id));

    }

 

    public Department getDepartmentById(int id) {

return em.find(Department.class, id);

    }

 

}

 

EmployeeLocal.java

package com.xavier.ejb3.sessionbean;

import com.xavier.ejb3.entitybean.Employee;

 

public interface EmployeeLocal {

public void addEmployee(String name, int age, String phone, int departmentid);

public Employee getEmployeeById(int id);

public void deleteEmployee(int id);

}

 

EmployeeBean.java

package com.xavier.ejb3.sessionbean;

import com.xavier.ejb3.entitybean.Department;

import com.xavier.ejb3.entitybean.Employee;

import javax.ejb.Local;

import javax.ejb.Stateless;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

 

@Stateless

@Local(EmployeeLocal.class)

public class EmployeeBean implements EmployeeLocal {

@PersistenceContext(unitName=“ejb3”)

protected EntityManager em;

    public void addEmployee(String name, int age, String phone, int departmentid) {

        Employee employee = new Employee();

        Department department = new Department();

        department.setId(departmentid);

        employee.setDepartment(department);

        employee.setName(name);

        employee.setAge(age);

        employee.setPhone(phone);

        em.persist(employee);

    }

 

    public Employee getEmployeeById(int id) {

return em.find(Employee.class, id);

    }

   

    public void deleteEmployee(int id){

        Employee employee = em.find(Employee.class, id);

        em.remove(employee);

    }

}

 

OneToManyTest.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 Many</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);

EmployeeLocal el = (EmployeeLocal) ctx

.lookup(“ejb:ejb3/ejb3//EmployeeBean!com.xavier.ejb3.sessionbean.EmployeeLocal”);

//Add Employee

/*el.addEmployee(“Xavier”, 29, “13400000000”, 1);

el.addEmployee(“Nathaniel”, 28, “13100000000”, 1);

el.addEmployee(“Joe”, 27, “13500000000”, 1);

el.addEmployee(“Brian”, 30, “13800000000”, 1);

el.addEmployee(“Javier”, 26, “13900000000”, 1);*/

out.println(“<br>—————————-Successfully Added!”);

//Get Employee

Employee e = (Employee) el.getEmployeeById(1);

out.println(“<br>————–Print Employee info whose id is <1>——————“);

out.println(“<br>ID: “ + e.getId());

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

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

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

out.println(“<br>Department: “ + e.getDepartment().getName());

out.println(“<br>————–Successfully query”);

//Delete Employee

el.deleteEmployee(1);

out.println(“<br>———delete successfully!”);

 

} 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).

 

OneToMany&ManyToOne Unidirectional Association

Remove Department.java @OneToMany annotation and Set<Employee> employees property.

 
Leave a comment

Posted by on 03/16/2012 in EJB

 

OneToOne Bidirectional & Unidirectional Association

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.

 
Leave a comment

Posted by on 03/15/2012 in EJB

 

EJB3 Entities Life Cycle Events

2 approaches to implement Entities Life Cycle Events:

A. Write Life Cycle events in external file.

EntityListenerLogger.java

package com.xavier.ejb3.entitylistener;

import javax.persistence.PostLoad;

import javax.persistence.PostPersist;

import javax.persistence.PrePersist;

import javax.persistence.PreUpdate;

import javax.persistence.PostUpdate;

import javax.persistence.PreRemove;

import javax.persistence.PostRemove;

 

public class EntityListenerLogger {

@PostLoad

public void postLoad(Object entity) {

System.out.println(“Entity{“ + entity.getClass().getName( ) + “} @PostLoad event occurs”);

}

@PrePersist

public void PreInsert(Object entity) {

System.out.println(“Entity{“ + entity.getClass().getName( )+ “} @PrePersist event occurs”);

}

@PostPersist

public void postInsert(Object entity) {

System.out.println(“Entity{“ + entity.getClass().getName( )+ “} @PostPersist event occurs”);

}

@PreUpdate

public void PreUpdate(Object entity) {

System.out.println(“Entity{“ + entity.getClass().getName( )+ “} @PreUpdate event occurs”);

}

@PostUpdate

public void PostUpdate(Object entity) {

System.out.println(“Entity{“ + entity.getClass().getName( )+ “} @PostUpdate event occurs”);

}

@PreRemove

public void PreRemove(Object entity) {

System.out.println(“Entity{“ + entity.getClass().getName( )+ “} @PreRemove event occurs”);

}

@PostRemove

public void PostRemove(Object entity) {

System.out.println(“Entity{“ + entity.getClass().getName( )+ “} @PostRemove event occurs”);

}

}

 

User.java

package com.xavier.ejb3.entitybean;

import java.io.Serializable;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.EntityListeners;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.Table;

import com.xavier.ejb3.entitylistener.EntityListenerLogger;

 

@SuppressWarnings(“serial”)

@Entity

@EntityListeners(EntityListenerLogger.class)

@Table(name=“user”)

public class User implements Serializable{

private int id;

private String name;

private int age;

private String phone;

private String address;

@Id

@GeneratedValue(strategy=GenerationType.IDENTITY)

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

@Column(nullable=false)

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@Column(nullable=true)

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

@Column(nullable=true)

public String getPhone() {

return phone;

}

public void setPhone(String phone) {

this.phone = phone;

}

@Column(nullable=true)

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

}

 

B. Write Life Cycle events in the Entities files.

User.java

package com.xavier.ejb3.entitybean;

import java.io.Serializable;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.EntityListeners;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.PostLoad;

import javax.persistence.PostPersist;

import javax.persistence.PostRemove;

import javax.persistence.PostUpdate;

import javax.persistence.PrePersist;

import javax.persistence.PreRemove;

import javax.persistence.PreUpdate;

import javax.persistence.Table;

import com.xavier.ejb3.entitylistener.EntityListenerLogger;

 

@SuppressWarnings(“serial”)

@Entity

@EntityListeners(EntityListenerLogger.class)

@Table(name=“user”)

public class User implements Serializable{

private int id;

private String name;

private int age;

private String phone;

private String address;

@Id

@GeneratedValue(strategy=GenerationType.IDENTITY)

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

@Column(nullable=false)

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@Column(nullable=true)

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

@Column(nullable=true)

public String getPhone() {

return phone;

}

public void setPhone(String phone) {

this.phone = phone;

}

@Column(nullable=true)

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

@PostLoad

public void postLoad( ) {

System.out.println(“Entity{“ + this.getClass().getName( ) + “} @PostLoad event occurs”);

}

@PrePersist

public void PreInsert( ) {

System.out.println(“Entity{“ + this.getClass().getName( )+ “} @PrePersist event occurs”);

}

@PostPersist

public void postInsert( ) {

System.out.println(“Entity{“ + this.getClass().getName( )+ “} @PostPersist event occurs”);

}

@PreUpdate

public void PreUpdate( ) {

System.out.println(“Entity{“ + this.getClass().getName( )+ “} @PreUpdate event occurs”);

}

@PostUpdate

public void PostUpdate( ) {

System.out.println(“Entity{“ + this.getClass().getName( )+ “} @PostUpdate event occurs”);

}

@PreRemove

public void PreRemove( ) {

System.out.println(“Entity{“ + this.getClass().getName( )+ “} @PreRemove event occurs”);

}

@PostRemove

public void PostRemove( ) {

System.out.println(“Entity{“ + this.getClass().getName( )+ “} @PostRemove event occurs”);

}   

}

 
Leave a comment

Posted by on 03/14/2012 in EJB

 

EJB3 Entities and JPA

User Table – MySQL

NAME TYPE NULLABLE KEY EXTRA
id int(11) NO PRI auto_increment
name varchar(10) NO    
age int(11) YES    
phone varchar(20) YES    
address varchar(50) 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.User</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>

User.java

package com.xavier.ejb3.entitybean;

import java.io.Serializable;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.EntityListeners;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.Table;

import com.xavier.ejb3.entitylistener.EntityListenerLogger;

 

@SuppressWarnings(“serial”)

@Entity

@Table(name=“user”)

public class User implements Serializable{

private int id;

private String name;

private int age;

private String phone;

private String address;

@Id

@GeneratedValue(strategy=GenerationType.IDENTITY)

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

@Column(nullable=false)

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@Column(nullable=true)

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

@Column(nullable=true)

public String getPhone() {

return phone;

}

public void setPhone(String phone) {

this.phone = phone;

}

@Column(nullable=true)

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

}

 

UserDao.java

package com.xavier.ejb3.sessionbean;

import java.util.List;

import com.xavier.ejb3.entitybean.User;

 

public interface UserDao {

public void insertUser(User user);

public void updateName(String newname, int userid);

public List<User> getUserByName(String username);

public void mergeUser(User user);

public void deleteUser(int userid);

public User getUserByID(int userid);

public List<User> getUserList();

}


UserDaoBean.java

package com.xavier.ejb3.sessionbean;

import java.util.List;

import javax.ejb.Local;

//import javax.ejb.Remote;

import javax.ejb.Stateless;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

import javax.persistence.PersistenceContextType;

import javax.persistence.Query;

import com.xavier.ejb3.entitybean.User;

 

@Stateless

@Local(UserDao.class)

public class UserDaoBean implements UserDao{

@PersistenceContext(unitName=“ejb3”, type=PersistenceContextType.TRANSACTION)

protected EntityManager em;

 

@Override

public void insertUser(User user) {

em.persist(user);

}

 

@Override

public void updateName(String newname, int userid) {

User user = em.find(User.class, userid);

if(user != null){

user.setName(newname);

}

}

 

@Override

public void mergeUser(User user) {

em.merge(user);

}

 

@Override

public void deleteUser(int userid) {

User user = em.find(User.class, userid);

if(user != null)

em.remove(user);

}

 

@Override

public User getUserByID(int userid) {

return em.find(User.class, userid);

}

 

@SuppressWarnings(“unchecked”)

@Override

public List<User> getUserList() {

Query query = em.createQuery(“select u from User u order by u.id asc”);

return (List<User>)query.getResultList();

}

@SuppressWarnings(“unchecked”)

@Override

public List<User> getUserByName(String username){

Query query = em.createQuery(“select u from User u where u.name = :name”);

query.setParameter(“name”, username);

return (List<User>) query.getResultList();

}

}

 

EntityBeanBean.jsp

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

pageEncoding=“UTF-8”%>

<%@ page

import=“com.xavier.ejb3.sessionbean.UserDao,com.xavier.ejb3.entitybean.User,
              javax.naming.*,java.util.Properties,java.util.Date,java.util.Hashtable,java.util.List”
%>

<!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>EntityBean Test</title>

</head>

<TABLE width=“80%”

style=”border-width: 1px; border-color: #000; border-style: dotted;”>

<TR bgcolor=“#DFDFDF”>

<TD>用户ID</TD>

<TD>用户名称</TD>

<TD>用户年龄</TD>

<TD>用户电话</TD>

<TD>家庭住址</TD>

</TR>

<%

try {

final Hashtable jndiProperties = new Hashtable();

jndiProperties.put(Context.URL_PKG_PREFIXES,

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

Context ctx = new InitialContext(jndiProperties);

UserDao userdao = (UserDao) ctx

.lookup(“ejb:ejb3/ejb3//UserDaoBean!com.xavier.ejb3.sessionbean.UserDao”);

 

//Insert User

/*User user1 = new User();

user1.setName(“Xavier”);

user1.setAge(29);

user1.setPhone(“13400000000”);

user1.setAddress(“Dalian”);

userdao.insertUser(user1);

User user2 = new User();

user2.setName(“Nathaniel”);

user2.setAge(28);

user2.setPhone(“13000000000”);

user2.setAddress(“Xiamen”);

userdao.insertUser(user2);*/

 

//Update User – ID 2

//userdao.updateName(“Nate”, 2);

 

//Get Users List by name

List<User> users = userdao.getUserByName(“Xavier”);

for (User user : users) {

out.println(“<TR><TD>” + user.getId() + “</TD><TD>”

+ user.getName() + “</TD><TD>” + user.getAge()

+ “</TD><TD>” + user.getPhone() + “</TD><TD>”

+ user.getAddress() + “</TD></TR>”);

}

 

/*List<User> users = userdao.getUserList();

for (User user : users) {

out.println(“<TR><TD>” + user.getId() + “</TD><TD>”

+ user.getName() + “</TD><TD>” + user.getAge()

+ “</TD><TD>” + user.getPhone() + “</TD><TD>”

+ user.getAddress() + “</TD></TR>”);

}*/

} catch (Exception e) {

out.println(e);

}

%>

</TABLE>

Note:

1. transaction-type in persistence.xml – JTA, RESOURCE_LOCAL. Default is JTA. If you are using JPA in Java EE container, transaction-type should be set as JTA. If you are using JPA outside of Java EE container, you need set it as RESOURCE_LOCAL.

 

2. EntityManager Interface JDK6.0

void clear()
          Clear the persistence context, causing all managed entities to become detached.
void close()
          Close an application-managed entity manager.
boolean contains(java.lang.Object entity)
          Check if the instance is a managed entity instance belonging to the current persistence context.
Query createNamedQuery(java.lang.String name)
          Create an instance of Query for executing a named query (in the Java Persistence query language or in native SQL).
<T> TypedQuery<T> createNamedQuery(java.lang.String name, java.lang.Class<T> resultClass)
            Create an instance of TypedQuery for executing a Java Persistence query language named query.
Query createNativeQuery(java.lang.String sqlString)
          Create an instance of Query for executing a native SQL statement, e.g., for update or delete.
Query createNativeQuery(java.lang.String sqlString, java.lang.Class resultClass)
          Create an instance of Query for executing a native SQL query.
Query createNativeQuery(java.lang.String sqlString, java.lang.String resultSetMapping)
          Create an instance of Query for executing a native SQL query.
<T> TypedQuery<T> createQuery(CriteriaQuery<T> criteriaQuery)
          Create an instance of TypedQuery for executing a criteria query.
Query createQuery(java.lang.String qlString)
          Create an instance of Query for executing a Java Persistence query language statement.
<T> TypedQuery<T> createQuery(java.lang.String qlString, java.lang.Class<T> resultClass)
          Create an instance of TypedQuery for executing a Java Persistence query language statement.
void detach(java.lang.Object entity)
          Remove the given entity from the persistence context, causing a managed entity to become detached.
<T> T find(java.lang.Class<T> entityClass, java.lang.Object primaryKey)
          Find by primary key.
<T> T find(java.lang.Class<T> entityClass, java.lang.Object primaryKey, LockModeType lockMode)
          Find by primary key and lock.
<T> T find(java.lang.Class<T> entityClass, java.lang.Object primaryKey, LockModeType lockMode, java.util.Map<java.lang.String,java.lang.Object> properties)
          Find by primary key and lock, using the specified properties.
<T> T find(java.lang.Class<T> entityClass, java.lang.Object primaryKey, java.util.Map<java.lang.String,java.lang.Object> properties)
          Find by primary key, using the specified properties.
void flush()
          Synchronize the persistence context to the underlying database.
CriteriaBuilder getCriteriaBuilder()
          Return an instance of CriteriaBuilder for the creation of CriteriaQuery objects.
java.lang.Object getDelegate()
          Return the underlying provider object for the EntityManager, if available.
EntityManagerFactory getEntityManagerFactory()
          Return the entity manager factory for the entity manager.
FlushModeType getFlushMode()
          Get the flush mode that applies to all objects contained in the persistence context.
LockModeType getLockMode(java.lang.Object entity)
          Get the current lock mode for the entity instance.
Metamodel getMetamodel()
          Return an instance of Metamodel interface for access to the metamodel of the persistence unit.
java.util.Map<java.lang.String,java.lang.Object> getProperties()
          Get the properties and hints and associated values that are in effect for the entity manager.
<T> T getReference(java.lang.Class<T> entityClass, java.lang.Object primaryKey)
          Get an instance, whose state may be lazily fetched.
EntityTransaction getTransaction()
          Return the resource-level EntityTransaction object.
boolean isOpen()
          Determine whether the entity manager is open.
void joinTransaction()
          Indicate to the entity manager that a JTA transaction is active.
void lock(java.lang.Object entity, LockModeType lockMode)
          Lock an entity instance that is contained in the persistence context with the specified lock mode type.
void lock(java.lang.Object entity, LockModeType lockMode, java.util.Map<java.lang.String,java.lang.Object> properties)
          Lock an entity instance that is contained in the persistence context with the specified lock mode type and with specified properties.
<T> T merge(T entity)
          Merge the state of the given entity into the current persistence context.
void persist(java.lang.Object entity)
          Make an instance managed and persistent.
void refresh(java.lang.Object entity)
          Refresh the state of the instance from the database, overwriting changes made to the entity, if any.
void refresh(java.lang.Object entity, LockModeType lockMode)
          Refresh the state of the instance from the database, overwriting changes made to the entity, if any, and lock it with respect to given lock mode type.
void refresh(java.lang.Object entity, LockModeType lockMode, java.util.Map<java.lang.String,java.lang.Object> properties)
          Refresh the state of the instance from the database, overwriting changes made to the entity, if any, and lock it with respect to given lock mode type and with specified properties.
void refresh(java.lang.Object entity, java.util.Map<java.lang.String,java.lang.Object> properties)
          Refresh the state of the instance from the database, using the specified properties, and overwriting changes made to the entity, if any.
void remove(java.lang.Object entity)
          Remove the entity instance.
void setFlushMode(FlushModeType flushMode)
          Set the flush mode that applies to all objects contained in the persistence context.
void setProperty(java.lang.String propertyName, java.lang.Object value)
          Set an entity manager property or hint.
<T> T unwrap(java.lang.Class<T> cls)
          Return an object of the specified type to allow access to the provider-specific API.

3. Create EntityManager Instance –

Approach 1 – Create Container Managed EntityManager Instance.

@PersistenceContext(unitName=“ejb3”)

protected EntityManager em;

EntityManager is not safe-thread. Please use it in EJB, not use it directly in Presentation Tier.

 

Approach 2 – Create Application Managed EntityManager Instance.

@PersistenceUnit(unitName=“ejb3”)

private EntityManagerFactory entityManagerFactory;

private EntityManager em;

@PostConstruct

public void initialize(){

em = entityManagerFactory.createEntityManager();

}

@PreDestroy

public void cleanup(){

if(em.isOpen()){

em.close();

}

}

 
Leave a comment

Posted by on 03/13/2012 in EJB