开发表音映射的实体
Java持久化规范(JPA),即是实体bean通远元数据在javaBean和数据库之间建立映射关系,常见的hibernate toplink openjpa
在src目录下添加META-INF/persistence.xml文件,示例代码如下:
<?xmlversion="1.0"encoding="UTF-8"?>
<persistencexmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unitname="retacn"transaction-type="JTA">
<!-- 使用oracle数据库 -->
<jta-data-source>java:/OracleDS</jta-data-source>
<properties>
<!-- 数据库方言 -->
<propertyname="hibernate.hbm2ddl.auto"value="update"/>
<propertyname="hibernate.format_sql"value="true"/>
<propertyname="hibernate.show_sql"value="true"/>
</properties>
</persistence-unit>
<persistence-unitname="local"transaction-type="JTA">
<!-- 使用mysql数据库 -->
<jta-data-source>java:/MySqlDS</jta-data-source>
<properties>
<!-- 数据库方言 -->
<propertyname="hibernate.hbm2ddl.auto"value="update"/>
<propertyname="hibernate.format_sql"value="true"/>
<propertyname="hibernate.show_sql"value="true"/>
</properties>
</persistence-unit>
</persistence>
使用oracle数据库
/**
* Copyright (C) 2016
*
* FileName:User.java
*
* Author:<a href="mailto:zhenhuayue@sina.com">Retacn</a>
*
* CreateTime: 2016-7-22
*/
// Package Information
package cn.yue.ejb.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
importjavax.persistence.GenerationType;
import javax.persistence.Id;
importjavax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* 用户 元数据的定义有两种方式: 1 xml的方式 2 注解的方式
*
* @version
* @Description:
* @author <ahref="mailto:zhenhuayue@sina.com">Retacn</a>
* @since 2016-7-22
*/
@Entity
@Table(name = "t_user")
public class User implementsSerializable {
private static final long serialVersionUID = 1L;
// @GeneratedValue表示主键的取值方式,这里采用序列的方式
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator ="mseq")
@SequenceGenerator(name = "mseq", sequenceName ="user_sequences", allocationSize = 1)
private long id;
@Column(length = 32)
private String user_name;
@Column(length = 32)
private String real_name;
@Column(length = 6)
private String user_age;
@Column(length = 16)
private String password;
@Column(length = 21)
private String phone;
@Column
@Temporal(TemporalType.DATE)
private Date regtime;
@Column(length = 32)
private String device_id;
@Column(length = 10)
private String visible;
@Column(length = 60)
private String email;
@Column(length = 32)
private String reserve1;
@Column(length = 32)
private String reserve2;
@Column(length = 32)
private String reserve3;
@Column(length = 32)
private String reserve4;
@Column(length = 32)
private String reserve5;
/**
* 构造器
*/
public User() {
}
public User(String user_name, String real_name, String password, Stringphone,
String device_id, String visible,
String email) {
this.user_name = user_name;
this.real_name = real_name;
this.password = password;
this.phone = phone;
this.device_id = device_id;
this.visible = visible;
this.email = email;
this.regtime = new Date();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getReal_name() {
return real_name;
}
public void setReal_name(String real_name) {
this.real_name = real_name;
}
public String getUser_age() {
return user_age;
}
public void setUser_age(String user_age) {
this.user_age = user_age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getRegtime() {
return regtime;
}
public void setRegtime(Date regtime) {
this.regtime = regtime;
}
public String getDevice_id() {
return device_id;
}
public void setDevice_id(String device_id) {
this.device_id = device_id;
}
public String getVisible() {
return visible;
}
public void setVisible(String visible) {
this.visible = visible;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getReserve1() {
return reserve1;
}
public void setReserve1(String reserve1) {
this.reserve1 = reserve1;
}
public String getReserve2() {
return reserve2;
}
public void setReserve2(String reserve2) {
this.reserve2 = reserve2;
}
public String getReserve3() {
return reserve3;
}
public void setReserve3(String reserve3) {
this.reserve3 = reserve3;
}
public String getReserve4() {
return reserve4;
}
public void setReserve4(String reserve4) {
this.reserve4 = reserve4;
}
public String getReserve5() {
return reserve5;
}
public void setReserve5(String reserve5) {
this.reserve5 = reserve5;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((device_id == null) ? 0 :device_id.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((password == null) ? 0 :password.hashCode());
result = prime * result + ((phone == null) ? 0 : phone.hashCode());
result = prime * result + ((real_name == null) ? 0 :real_name.hashCode());
result = prime * result + ((regtime == null) ? 0 : regtime.hashCode());
result = prime * result + ((reserve1 == null) ? 0 :reserve1.hashCode());
result = prime * result + ((reserve2 == null) ? 0 :reserve2.hashCode());
result = prime * result + ((reserve3 == null) ? 0 :reserve3.hashCode());
result = prime * result + ((reserve4 == null) ? 0 :reserve4.hashCode());
result = prime * result + ((reserve5 == null) ? 0 :reserve5.hashCode());
result = prime * result + ((user_age == null) ? 0 :user_age.hashCode());
result = prime * result + ((user_name == null) ? 0 :user_name.hashCode());
result = prime * result + ((visible == null) ? 0 : visible.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;
User other = (User) obj;
if (device_id == null) {
if (other.device_id != null)
return false;
} else if (!device_id.equals(other.device_id))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (id != other.id)
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (phone == null) {
if (other.phone != null)
return false;
} else if (!phone.equals(other.phone))
return false;
if (real_name == null) {
if (other.real_name != null)
return false;
} else if (!real_name.equals(other.real_name))
return false;
if (regtime == null) {
if (other.regtime != null)
return false;
} else if (!regtime.equals(other.regtime))
return false;
if (reserve1 == null) {
if (other.reserve1 != null)
return false;
} else if (!reserve1.equals(other.reserve1))
return false;
if (reserve2 == null) {
if (other.reserve2 != null)
return false;
} else if (!reserve2.equals(other.reserve2))
return false;
if (reserve3 == null) {
if (other.reserve3 != null)
return false;
} else if (!reserve3.equals(other.reserve3))
return false;
if (reserve4 == null) {
if (other.reserve4 != null)
return false;
} else if (!reserve4.equals(other.reserve4))
return false;
if (reserve5 == null) {
if (other.reserve5 != null)
return false;
} else if (!reserve5.equals(other.reserve5))
return false;
if (user_age == null) {
if (other.user_age != null)
return false;
} else if (!user_age.equals(other.user_age))
return false;
if (user_name == null) {
if (other.user_name != null)
return false;
} else if (!user_name.equals(other.user_name))
return false;
if (visible == null) {
if (other.visible != null)
return false;
} else if (!visible.equals(other.visible))
return false;
return true;
}
@Override
public String toString() {
return "User [id=" + id + ", user_name=" + user_name+ ", real_name=" + real_name
+ ", user_age=" +user_age + ", password=" + password + ", phone=" + phone
+ ", regtime=" +regtime + ", device_id=" + device_id + ", visible=" +visible
+ ", email=" + email+ ", reserve1=" + reserve1 + ", reserve2=" + reserve2
+ ", reserve3=" +reserve3 + ", reserve4=" + reserve4 + ", reserve5=" +reserve5
+ "]";
}
}
/**
* Copyright (C) 2016
*
* FileName:UserService.java
*
* Author:<ahref="mailto:zhenhuayue@sina.com">Retacn</a>
*
* CreateTime: 2016-7-22
*/
// Package Information
package cn.yue.ejb.service;
import java.util.List;
import cn.yue.ejb.entity.User;
/**
* 用户操作实体
*
* @version
* @Description:
* @author <ahref="mailto:zhenhuayue@sina.com">Retacn</a>
* @since 2016-7-22
*/
public interface UserService {
public void save(User user);
public void delete(long id);
public void update(User user);
public User getById(long id);
public User getReferencesById(long id);
public List<User> getAllUsers();
}
/**
* Copyright (C) 2016
*
* FileName:UserServiceBean.java
*
* Author:<a href="mailto:zhenhuayue@sina.com">Retacn</a>
*
* CreateTime: 2016-7-22
*/
// Package Information
package cn.yue.ejb.service.impl;
import java.util.List;
import javax.ejb.Remote;
import javax.ejb.Stateless;
importjavax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import cn.yue.ejb.entity.User;
import cn.yue.ejb.service.UserService;
/**
* 用户操作 ,此服务为无状态会话bean
*
* @version
* @Description:
* @author <ahref="mailto:zhenhuayue@sina.com">Retacn</a>
* @since 2016-7-22
*/
@Stateless
@Remote(UserService.class)
public class UserServiceBeanimplements UserService {
/**
* 实体管理器unitName="" 指定持久化单元,使用oracle数据源, 如果只有一个持久化单元,该属性可以省略
**/
@PersistenceContext(unitName = "retacn")
EntityManager em;
/**
* 保存用户
*/
@Override
public void save(User user) {
// 新建状态变为托管状态
em.persist(user);
}
/**
* 删除用户
*/
@Override
public void delete(long id) {
// 由托管状态变为销毁状态
em.remove(getReferencesById(id));
}
/**
* 更新用户
*/
@Override
public void update(User user) {
// 由游离状态变为托管状态
em.merge(user);
}
/**
* 根据id查询用户
*/
@Override
public User getById(long id) {
return em.find(User.class, id);
}
@Override
public User getReferencesById(long id) {
// 懒加载返回代理对象,只有在使用get方法获取数据时,对会加载对象
return em.getReference(User.class, id);
}
/**
* 查询所有用户
*/
@SuppressWarnings("unchecked")
@Override
public List<User> getAllUsers() {
// 使用jpql查询结果集
return (List<User>) em.createQuery("select u from Useru").getResultList();
}
}
修改build.xml文件
<copytodir="${build.dir}">
<filesetdir="${src.dir}">
<includename="META-INF"/>
<includename="META-INF/"/>
<includename="META-INF/**"/>
<includename="META-INF/***"/>
</fileset>
</copy>
如果是编译的是jar文件,可以直接使用<metainf></metainf>
客户端测试代码如下:
/**
* Copyright (C) 2016
*
* FileName:UserServiceTest.java
*
* Author:<ahref="mailto:zhenhuayue@sina.com">Retacn</a>
*
* CreateTime: 2016-7-22
*/
// Package Information
packagecn.yue.ejb.test;
importcn.yue.ejb.entity.User;
importcn.yue.ejb.service.UserService;
import org.junit.BeforeClass;
import org.junit.Test;
importjava.util.Hashtable;
import java.util.List;
importjavax.naming.Context;
importjavax.naming.InitialContext;
/**
* 测试用户操作
*
* @version
* @Description:
* @author <ahref="mailto:zhenhuayue@sina.com">Retacn</a>
* @since 2016-7-22
*/
public classUserServiceTest {
private static UserService userService;
@SuppressWarnings("unchecked")
@BeforeClass
public static void setUpBeforeClass()throws Exception {
@SuppressWarnings("rawtypes")
final Hashtable jndiProperties = newHashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES,"org.jboss.ejb.client.naming");
final Context context = newInitialContext(jndiProperties);
// 如果服务器布署的是.ear包,则appname为.ear之后的包名,如果的war或是jar包,appName可以为空
final String appName = "";
final String moduleName ="HelloWorldEJB";
final String distinctName ="";
final String beanName ="UserServiceBean";
final String viewClassName = UserService.class.getName();
final String namespace ="ejb:" + appName + "/" + moduleName + "/" +distinctName + "/"
+ beanName + "!" +viewClassName;
System.out.println("namespace:" + namespace);
userService = (UserService)context.lookup(namespace);
System.out.println(userService);
}
@Test
public void testSave() {
userService.save(newUser("retacn", "岳振华", "123456", "1234567","3333", "T",
"loveyou.for.ever@163.com"));
}
@Test
public void testDelete() {
userService.delete(280);
}
@Test
public void testUpdate() {
User user = userService.getById(305);
user.setReal_name("岳老三");
userService.update(user);
}
@Test
public void testGetById() {
User user = userService.getById(305);
System.out.println(user.toString());
}
@Test
public void testGetReferencesById() {
}
@Test
public void testGetAllUsers() {
List<User> users =userService.getAllUsers();
for (User user : users) {
System.out.println(user.toString());
}
}
}
使用mysql数据库
/**
* Copyright (C) 2016
*
* FileName:Buyer.java
*
* Author:<ahref="mailto:zhenhuayue@sina.com">Retacn</a>
*
* CreateTime: 2016-7-23
*/
// Package Information
package cn.yue.ejb.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* 购物者
*
* @version
* @Description:
* @author <ahref="mailto:zhenhuayue@sina.com">Retacn</a>
* @since 2016-7-23
*/
@Entity
@Table(name = "buyer")
public class Buyer implementsSerializable {
private static final long serialVersionUID = 1L;
/** 用户名 **/
@Id
@Column(name = "userName")
private String userName;
/** 邮箱 **/
@Column(length = 30)
private String email;
/** 性别 **/
@Column(length = 5)
private String gender;
/** 密码 **/
@Column(length = 32)
private String password;
/** 真实姓名 **/
@Column(length = 30)
private String realName;
/** 注册时间 **/
@Column(length = 30)
@Temporal(TemporalType.TIMESTAMP)
private Date regTime = new Date();
/** 是否可用 **/
@Column(length = 1)
private boolean visible = true;
/** 暂不使用 **/
@Column(length = 11)
private String contact_id;
/**
* 构造器
*/
public Buyer() {
}
public Buyer(String userName,//
String email,//
String gender, //
String password,//
String realName) {
this.userName = userName;
this.email = email;
this.gender = gender;
this.password = password;
this.realName = realName;
this.regTime = new Date();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public Date getRegTime() {
return regTime;
}
public void setRegTime(Date regTime) {
this.regTime = regTime;
}
public boolean getVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public String getContact_id() {
return contact_id;
}
public void setContact_id(String contact_id) {
this.contact_id = contact_id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((contact_id == null) ? 0 : contact_id.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((gender == null) ? 0 : gender.hashCode());
result = prime * result + ((password == null) ? 0 : password.hashCode());
result = prime * result + ((realName == null) ? 0 :realName.hashCode());
result = prime * result + ((regTime == null) ? 0 : regTime.hashCode());
result = prime * result + ((userName == null) ? 0 :userName.hashCode());
result = prime * result + (visible ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Buyer other = (Buyer) obj;
if (contact_id == null) {
if (other.contact_id != null)
return false;
} else if (!contact_id.equals(other.contact_id))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (gender == null) {
if (other.gender != null)
return false;
} else if (!gender.equals(other.gender))
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (realName == null) {
if (other.realName != null)
return false;
} else if (!realName.equals(other.realName))
return false;
if (regTime == null) {
if (other.regTime != null)
return false;
} else if (!regTime.equals(other.regTime))
return false;
if (userName == null) {
if (other.userName != null)
return false;
} else if (!userName.equals(other.userName))
return false;
if (visible != other.visible)
return false;
return true;
}
@Override
public String toString() {
return "Buyer [userName=" + userName + ", email=" +email + ", gender=" + gender
+ ", password=" +password + ", realName=" + realName + ", regTime=" +regTime
+ ", visible=" +visible + ", contact_id=" + contact_id + "]";
}
}
/**
* Copyright (C) 2016
*
* FileName:BuyerService.java
*
* Author:<ahref="mailto:zhenhuayue@sina.com">Retacn</a>
*
* CreateTime: 2016-7-23
*/
// Package Information
package cn.yue.ejb.service;
import cn.yue.ejb.entity.Buyer;
import java.util.List;
/**
* 购物者操作接口
*
* @version
* @Description:
* @author <ahref="mailto:zhenhuayue@sina.com">Retacn</a>
* @since 2016-7-23
*/
public interface BuyerService {
/**
* 保存购物者
*
* @param buyer
*/
public void save(Buyer buyer);
/**
* 删除购物者
*
* @param name
*/
public void delete(String name);
/**
* 更新购物者
*
* @param buyer
*/
public void update(Buyer buyer);
/**
* 根据用户名查询购物者
*
* @param name
* @return
*/
public Buyer getById(String name);
/**
* 根据用户名查询购物者(懒加载)
*
* @param name
* @return
*/
public Buyer getReferencesById(String name);
/**
* 查询所有购物者
*
* @return
*/
public List<Buyer> getAllBuyers();
}
/**
* Copyright (C) 2016
*
* FileName:BuyerServiceBean.java
*
* Author:<ahref="mailto:zhenhuayue@sina.com">Retacn</a>
*
* CreateTime: 2016-7-23
*/
// Package Information
package cn.yue.ejb.service.impl;
import java.util.List;
import javax.ejb.Remote;
import javax.ejb.Stateless;
importjavax.persistence.EntityManager;
importjavax.persistence.PersistenceContext;
import cn.yue.ejb.entity.Buyer;
import cn.yue.ejb.service.BuyerService;
/**
* 购物者操作接口实现类(无状态bean )
*
* @version
* @Description:
* @author <ahref="mailto:zhenhuayue@sina.com">Retacn</a>
* @since 2016-7-23
*/
@Stateless
@Remote(BuyerService.class)
public class BuyerServiceBeanimplements BuyerService {
/** 主入实体管理bean **/
@PersistenceContext(unitName = "local")
EntityManager em;
@Override
public void save(Buyer buyer) {
em.persist(buyer);
}
@Override
public void delete(String name) {
em.remove(getReferencesById(name));
}
@Override
public void update(Buyer buyer) {
em.merge(buyer);
}
@Override
public Buyer getById(String name) {
return em.find(Buyer.class, name);
}
@Override
public Buyer getReferencesById(String name) {
return em.getReference(Buyer.class, name);
}
@SuppressWarnings("unchecked")
@Override
public List<Buyer> getAllBuyers() {
return (List<Buyer>) em.createQuery("select b from Buyerb").getResultList();
}
}
客户端测试代码如下:
/**
* Copyright (C) 2016
*
* FileName:BuyerServiceTest.java
*
* Author:<ahref="mailto:zhenhuayue@sina.com">Retacn</a>
*
* CreateTime: 2016-7-23
*/
// Package Information
package cn.yue.ejb.test;
import cn.yue.ejb.entity.Buyer;
importcn.yue.ejb.service.BuyerService;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Hashtable;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
/**
* 购物者业务测试类
*
* @version
* @Description:
* @author <ahref="mailto:zhenhuayue@sina.com">Retacn</a>
* @since 2016-7-23
*/
public class BuyerServiceTest {
private static BuyerService buyerService;
@SuppressWarnings("unchecked")
@BeforeClass
public static void setUpBeforeClass() throws Exception {
@SuppressWarnings("rawtypes")
final Hashtable jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES,"org.jboss.ejb.client.naming");
final Context context = new InitialContext(jndiProperties);
// 如果服务器布署的是.ear包,则appname为.ear之后的包名,如果的war或是jar包,appName可以为空
final String appName = "";
final String moduleName = "HelloWorldEJB";
final String distinctName = "";
final String beanName ="BuyerServiceBean";
final String viewClassName = BuyerService.class.getName();
final String namespace = "ejb:" + appName + "/" +moduleName + "/" + distinctName + "/"
+ beanName + "!" +viewClassName;
System.out.println("namespace:" + namespace);
buyerService = (BuyerService) context.lookup(namespace);
System.out.println(buyerService);
}
@Test
public void testSave() {
buyerService.save(new Buyer("retacn1","loveyou.for.ever@163.com", "MAN", "123456","岳振华"));
}
@Test
public void testDelete() {
buyerService.delete("retacn1");
}
@Test
public void testUpdate() {
Buyer buyer = buyerService.getById("retacn1");
buyer.setRealName("岳老三");
buyerService.update(buyer);
}
@Test
public void testGetById() {
Buyer buyer = buyerService.getById("retacn1");
System.out.println(buyer.toString());
}
@Test
public void testGetReferencesById() {
}
@Test
public void testGetAllBuyers() {
List<Buyer> buyers = buyerService.getAllBuyers();
for (Buyer buyer : buyers) {
System.out.println(buyer.toString());
}
}
}