RSS

EJB3 Entities and JPA

13 Mar

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();

}

}

Advertisements
 
Leave a comment

Posted by on 03/13/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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s

 
%d bloggers like this: