实体Bean--将简单的POJO通过注解的方法进行ORM(对象-关系)的映射,更多的看看JPA2.0手册吧
实体的四种状态 还是比较重要的
The entity lifecycle is managed by the underlying persistence provider.
New (transient): an entity is new if it has just been instantiated using the new operator, and it is not associated with a persistence context. It has no persistent representation in the database and no identifier value has been assigned.
Managed (persistent): a managed entity instance is an instance with a persistent identity that is currently associated with a persistence context.
Detached: the entity instance is an instance with a persistent identity that is no longer associated with a persistence context, usually because the persistence context was closed or the instance was evicted from the context.
Removed: a removed entity instance is an instance with a persistent identity, associated with a persistence context, but scheduled for removal from the database.
一样的 一个简单的例子 介绍 内容
还是从EJB的提供者会话bean开始吧
package com.undergrowth.hello.impl;
import java.util.List;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.undergrowth.bean.Student;
import com.undergrowth.hello.StudentService;
/**
* 将此服务类转为无状态的会话bean 操作 实体bean
* @author Administrator
*
*/
@Stateless
@Remote(StudentService.class)
public class StudentServiceBean implements StudentService {
//依赖注入实体管理器
@PersistenceContext EntityManager em;
@Override
public void save(Student student) {
// TODO Auto-generated method stub
//由新建状态转为托管状态
em.persist(student);
}
@Override
public void delete(Integer id) {
// TODO Auto-generated method stub
//有托管状态转为销毁状态
em.remove(getReferencesById(id));
}
@Override
public void update(Student student) {
// TODO Auto-generated method stub
//由游离态转为托管状态
em.merge(student);
}
@Override
public Student getById(Integer id) {
// TODO Auto-generated method stub
return em.find(Student.class, id);
}
@SuppressWarnings("unchecked")
@Override
public List<Student> getAllStudents() {
// TODO Auto-generated method stub
//使用JPQL进行查询结果集
return (List<Student>)em.createQuery("select s from Student s").getResultList();
}
@Override
public Student getReferencesById(Integer id) {
// TODO Auto-generated method stub
//使用懒加载 返回代理对象 只有在使用get方法获取数据时 才加载对象
return em.getReference(Student.class, id);
}
}
使用PersistenceContext进行注入JPA的实体管理器 用管理实体的上下文
package com.undergrowth.hello;
import java.util.List;
import com.undergrowth.bean.Student;
/**
* 对Student实体进行CRUD
* @author Administrator
*
*/
public interface StudentService {
public void save(Student student);
public void delete(Integer id);
public void update(Student student);
public Student getById(Integer id);
public Student getReferencesById(Integer id);
public List<Student> getAllStudents();
}
package com.undergrowth.bean;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* 实体对象 将Student的POJO与表student进行ORM的映射
* 实现Serializable接口在于 可将此Student对象进行远程传输
* @author Administrator
*
*/
@Entity
@Table(name="student")
public class Student implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @Id 表示表的主键对应的POJO的字段
* @GeneratedValue 表示主键的取值方式 此地连接的是oracle11g 采用序列的方式 为主键赋值
*/
@Id @GeneratedValue(strategy=GenerationType.SEQUENCE)
private Integer id;
/**
* 指定列的长度为20个字符
*/
@Column(length=20)
private String NAME;
/**
* 以日期格式建立 精确到时分秒
*/
@Column @Temporal(TemporalType.DATE)
private Date birthday;
@Column
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNAME() {
return NAME;
}
public void setNAME(String nAME) {
NAME = nAME;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return "Student [id=" + id + ", NAME=" + NAME + ", birthday="
+ birthday + ", age=" + age + "]";
}
}
<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_2_0.xsd"
version="2.0">
<persistence-unit name="under" transaction-type="JTA">
<jta-data-source>java:/myDataSource</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
使用ant 打包发布到jboss中 并打包接口给第三方使用 build.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- ================================================ -->
<!-- Sample buildfile for jar components -->
<!-- -->
<!-- ================================================ -->
<project name="HelloWorld" basedir=".">
<!-- 定义属性 -->
<property name="src.dir" value="${basedir}\src" />
<property environment="env" />
<property name="jboss.home" value="${env.JBOSS_HOME}"/>
<property name="jboss.server.home" value="standalone" />
<property name="dep" value="deployments" />
<property name="build.dir" value="${basedir}\build" />
<path id="build.classpath">
<fileset dir="${basedir}\lib">
<include name="*.jar" />
</fileset>
<pathelement location="${build.dir}" />
</path>
<!-- - - - - - - - - - - - - - -->
<!-- target: init -->
<!-- - - - - - - - - - - - - - -->
<target name="init">
<delete dir="${build.dir}"></delete>
<mkdir dir="${build.dir}"></mkdir>
</target>
<!-- ========================= -->
<!-- target: compile -->
<!-- ========================= -->
<target name="compile" depends="init"
description="--> compile this component" >
<javac srcdir="${src.dir}" destdir="${build.dir}" includes="com/**">
<classpath refid="build.classpath" />
</javac>
</target>
<!-- 打包 -->
<target name="ejbjar" depends="compile" description="打包ejb">
<jar jarfile="${basedir}\${ant.project.name}.jar">
<fileset dir="${build.dir}">
<include name="**/*.class"></include>
</fileset>
<metainf dir="${src.dir}\META-INF"></metainf>
</jar>
</target>
<!-- 部署 -->
<target name="delopy" depends="ejbjar" description="部署ejb">
<copy file="${basedir}\${ant.project.name}.jar" todir="${jboss.home}\${jboss.server.home}\${dep}\" />
</target>
<!-- 卸载ejb -->
<target name="undeploy" description="卸载ejb">
<delete file="${jboss.home}\${jboss.server.home}\${dep}\${ant.project.name}.jar"></delete>
</target>
<!-- 打包接口 -->
<target name="package_inter" depends="compile" description="打包接口">
<jar jarfile="${basedir}\${ant.project.name}Interface.jar">
<fileset dir="${build.dir}">
<exclude name="**/impl/*.class"></exclude>
</fileset>
</jar>
</target>
</project>
jboss中信息
19:22:04,634 INFO [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-2) JNDI bindings for session bean named StudentServiceBean in deployment unit deployment "HelloWorld.jar" are as follows:
java:global/HelloWorld/StudentServiceBean!com.undergrowth.hello.StudentService
java:app/HelloWorld/StudentServiceBean!com.undergrowth.hello.StudentService
java:module/StudentServiceBean!com.undergrowth.hello.StudentService
java:jboss/exported/HelloWorld/StudentServiceBean!com.undergrowth.hello.StudentService
java:global/HelloWorld/StudentServiceBean
java:app/HelloWorld/StudentServiceBean
java:module/StudentServiceBean
解析持久化单元
19:22:04,885 INFO [org.hibernate.ejb.Ejb3Configuration] (MSC service thread 1-3) HHH000204: Processing PersistenceUnitInfo [
name: under
...]
19:22:04,883 INFO [org.jboss.ws.common.management.DefaultEndpointRegistry] (MSC service thread 1-1) register: jboss.ws:context=HelloWorld,endpoint=WebServicesEjbTestBean
19:22:04,889 INFO [org.jboss.as.ejb3] (MSC service thread 1-2) JBAS014142: Started message driven bean 'JmsMessageConsumer' with 'hornetq-ra' resource adapter
19:22:04,900 INFO [org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator] (MSC service thread 1-3) HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
19:22:04,913 INFO [org.hibernate.dialect.Dialect] (MSC service thread 1-3) HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
19:22:04,917 INFO [org.hibernate.engine.transaction.internal.TransactionFactoryInitiator] (MSC service thread 1-3) HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory
19:22:04,919 INFO [org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory] (MSC service thread 1-3) HHH000397: Using ASTQueryTranslatorFactory
19:22:04,931 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (MSC service thread 1-3) HHH000228: Running hbm2ddl schema update
19:22:04,932 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (MSC service thread 1-3) HHH000102: Fetching database metadata
19:22:05,993 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (MSC service thread 1-3) HHH000396: Updating schema
19:22:06,011 INFO [org.hibernate.tool.hbm2ddl.TableMetadata] (MSC service thread 1-3) HHH000261: Table found: U1.STUDENT
19:22:06,013 INFO [org.hibernate.tool.hbm2ddl.TableMetadata] (MSC service thread 1-3) HHH000037: Columns: [id, birthday, age, name]
19:22:06,014 INFO [org.hibernate.tool.hbm2ddl.TableMetadata] (MSC service thread 1-3) HHH000108: Foreign keys: []
19:22:06,015 INFO [org.hibernate.tool.hbm2ddl.TableMetadata] (MSC service thread 1-3) HHH000126: Indexes: [sys_c0010798]
19:22:06,016 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (MSC service thread 1-3) HHH000232: Schema update complete
19:22:06,189 INFO [org.jboss.web] (MSC service thread 1-2) JBAS018210: Registering web context: /HelloWorld
19:22:06,660 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS018559: Deployed "HelloWorld.jar"
最终的客户端调用代码
package com.undergrowth.ejb3.client;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.undergrowth.bean.Student;
import com.undergrowth.hello.StudentService;
/**
* 获取EJB服务 对Student对象进行CRUD操作
* @author Administrator
*
*/
public class StudentClient {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
StudentService ss=lookupRemoteHelloWorldBean();
//student的CRUD操作
System.out.println("添加前查询");
//R 查询
List<Student> liStudents=ss.getAllStudents();
for (Student student2 : liStudents) {
System.out.println(student2);
}
Student student=initStudent();
//C 添加
ss.save(student);
System.out.println("添加后查询");
//R 查询
liStudents=ss.getAllStudents();
for (Student student2 : liStudents) {
System.out.println(student2);
}
//U 更新
student=ss.getById(5);
student.setNAME("Eason");
ss.update(student);
System.out.println("更新后查询");
//R 查询
liStudents=ss.getAllStudents();
for (Student student2 : liStudents) {
System.out.println(student2);
}
//D 删除
ss.delete(6);
System.out.println("删除后查询");
//R 查询
liStudents=ss.getAllStudents();
for (Student student2 : liStudents) {
System.out.println(student2);
}
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 初始化操作
* @return
*/
private static Student initStudent() {
Student student=new Student();
student.setNAME("华仔");
student.setAge(56);
student.setBirthday(new Date());
return student;
}
/**
* 在jboss中查找到jndi里发布的服务
* @return
* @throws NamingException
*/
public static StudentService lookupRemoteHelloWorldBean() throws NamingException {
final Hashtable jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
final Context context = new InitialContext(jndiProperties);
// The app name is the application name of the deployed EJBs. This is typically the ear name
// without the .ear suffix. However, the application name could be overridden in the application.xml of the
// EJB deployment on the server.
// Since we haven't deployed the application as a .ear, the app name for us will be an empty string
final String appName = "";
// This is the module name of the deployed EJBs on the server. This is typically the jar name of the
// EJB deployment, without the .jar suffix, but can be overridden via the ejb-jar.xml
// In this example, we have deployed the EJBs in a jboss-as-ejb-remote-app.jar, so the module name is
// jboss-as-ejb-remote-app
final String moduleName = "HelloWorld";
// AS7 allows each deployment to have an (optional) distinct name. We haven't specified a distinct name for
// our EJB deployment, so this is an empty string
final String distinctName = "";
// The EJB name which by default is the simple class name of the bean implementation class
final String beanName = "StudentServiceBean";
// the remote view fully qualified class name
// final String viewClassName = HelloWorldRemote.class.getName();
final String viewClassName = StudentService.class.getName();
// let's do the lookup
return (StudentService) context.lookup("ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName);
}
}
十月 29, 2014 7:43:36 下午 org.jboss.ejb.client.EJBClient <clinit>
INFO: JBoss EJB Client version 1.0.5.Final
添加前查询
十月 29, 2014 7:43:36 下午 org.xnio.Xnio <clinit>
INFO: XNIO Version 3.0.3.GA
十月 29, 2014 7:43:36 下午 org.xnio.nio.NioXnio <clinit>
INFO: XNIO NIO Implementation Version 3.0.3.GA
十月 29, 2014 7:43:36 下午 org.jboss.remoting3.EndpointImpl <clinit>
INFO: JBoss Remoting version 3.2.3.GA
十月 29, 2014 7:43:37 下午 org.jboss.ejb.client.remoting.VersionReceiver handleMessage
INFO: Received server version 1 and marshalling strategies [river]
十月 29, 2014 7:43:37 下午 org.jboss.ejb.client.remoting.RemotingConnectionEJBReceiver associate
INFO: Successful version handshake completed for receiver context EJBReceiverContext{clientContext=org.jboss.ejb.client.EJBClientContext@7b745a, receiver=Remoting connection EJB receiver [connection=Remoting connection <19dc72f>,channel=jboss.ejb,nodename=win-2nh7bqab7hp]} on channel Channel ID f4e2973a (outbound) of Remoting connection 00cfd5ee to localhost/127.0.0.1:4447
十月 29, 2014 7:43:37 下午 org.jboss.ejb.client.remoting.ChannelAssociation$ResponseReceiver handleMessage
WARN: Unsupported message received with header 0xffffffff
Student [id=5, NAME=华仔, birthday=2014-10-29, age=56]
Student [id=6, NAME=华仔, birthday=2014-10-29, age=56]
添加后查询
Student [id=5, NAME=华仔, birthday=2014-10-29, age=56]
Student [id=6, NAME=华仔, birthday=2014-10-29, age=56]
Student [id=7, NAME=华仔, birthday=2014-10-29, age=56]
更新后查询
Student [id=5, NAME=Eason, birthday=2014-10-29, age=56]
Student [id=6, NAME=华仔, birthday=2014-10-29, age=56]
Student [id=7, NAME=华仔, birthday=2014-10-29, age=56]
删除后查询
Student [id=5, NAME=Eason, birthday=2014-10-29, age=56]
Student [id=7, NAME=华仔, birthday=2014-10-29, age=56]
十月 29, 2014 7:43:37 下午 org.jboss.ejb.client.remoting.ChannelAssociation$ResponseReceiver handleEnd
INFO: Channel Channel ID f4e2973a (outbound) of Remoting connection 00cfd5ee to localhost/127.0.0.1:4447 can no longer process messages
即完成实体Bean的CRUD操作
哦 jboss的jndi连接服务器参数文件 在src下 jboss-ejb-client.properties
endpoint.name=client-endpoint
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false
remote.connections=default
remote.connection.default.host= localhost
remote.connection.default.port = 4447
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
remote.connection.default.username=qq
remote.connection.default.password=q
记录学习的脚步