如何在Java SE环境下使用JPA1.0?
Java Persistence API 1.0( EJB3 Entity Bean) 在Java EE5中, Entity Bean做为EJB规范中负责持久化的组件将逐渐成为一个历史名词了,作为J2EE 4规范中最为人所垢病的Entity Bean在Java EE5中被推到重来,取而代之的是java开发的通用持久化规范Java Persistence API 1.0。JPA作为java中负责关系数据持久化的组件已经完全独立出来成为一个单独的规范,而不再属于Enterprise Java Bean的范畴。
Java Persistence AP(JPA)可以说是java持久化技术的一个集大成者,它吸取了Hiberante,JDO,TopLink等优秀技术和框架,将这几年发展成熟起来的基于POJO模型的O/R Mapping技术标准化,成为在J2EE和J2SE环境中通用的java持久化API。值得注意的是Java Persistence API并不是J2EE环境专用,而是在java中的通用API。意味着我们可以在任何需要访问关系数据库的地方使用JPA,甚至包括swing开发的桌面应用。JPA也不要求一定在J2EE容器中才能运行,而是任何有JVM的环境都可以运用。这就使得我们可以很容易的把JPA作为一个持久化组件自由地和各种容器/框架(EJB3容器, Spring等等)组合。
下面是我做的一个JPA 在 Java SE 环境下的使用范例.
一、搭建环境
1) 搭建数据库环境
1、安装数据库(MySQL 5.0.24), 用户: root,密码: (空) 。2、建库piscesdb。
3、建表address:
droptableaddress;
createtableaddress(
addressIDintnotnull,
cityvarchar(55)notnull,
streetvarchar(55)NOTNULL,
zipvarchar(8)NOTNULL,
PRIMARYKEY(addressID)
);
insertintoaddressvalues(1,"深圳","坂田市场","518001");
insertintoaddressvalues(2,"深圳","坂田路口","518002");
insertintoaddressvalues(3,"深圳","四季花城","518003");
createtableaddress(
addressIDintnotnull,
cityvarchar(55)notnull,
streetvarchar(55)NOTNULL,
zipvarchar(8)NOTNULL,
PRIMARYKEY(addressID)
);
insertintoaddressvalues(1,"深圳","坂田市场","518001");
insertintoaddressvalues(2,"深圳","坂田路口","518002");
insertintoaddressvalues(3,"深圳","四季花城","518003");
4、建表userinfo:
droptableuserinfo;
createtableuserinfo(
userIDintnotnull,/**用户id*/
usernamevarchar(20)notnull,/**姓名*/
birthdaydatetimenull,/**出生日期*/
sexvarchar(8)notnull,/**性别*/
addressIDintnotnull,/**地址id*/
PRIMARYKEY(userID)
);
insertintouserinfovalues(1,"张先生",null,"male",1);
insertintouserinfovalues(2,"李某某",null,"male",2);
insertintouserinfovalues(3,"王某某",'2006-08-10',"female",3);
insertintouserinfovalues(4,"陈某某",'2006-08-12',"male",3);
createtableuserinfo(
userIDintnotnull,/**用户id*/
usernamevarchar(20)notnull,/**姓名*/
birthdaydatetimenull,/**出生日期*/
sexvarchar(8)notnull,/**性别*/
addressIDintnotnull,/**地址id*/
PRIMARYKEY(userID)
);
insertintouserinfovalues(1,"张先生",null,"male",1);
insertintouserinfovalues(2,"李某某",null,"male",2);
insertintouserinfovalues(3,"王某某",'2006-08-10',"female",3);
insertintouserinfovalues(4,"陈某某",'2006-08-12',"male",3);
2) 获取额外的jar包
下载JPA的实现类, 去https://glassfish.dev.java.net/downloads/persistence/JavaPersistence.html下载GlassFish v1 FCS branch版本,进行安装后得到toplink-essentials.jar,toplink-essentials-agent.jar 两个包,将这两个包和mysql的驱动包加入到项目的classpath路径中去。
编译toplink源码需要 javax.transaction、org.apache.tools.ant 两个包
项目工程路径不要含中文, 因为 toplink 暂时不支持。
3) 开发环境
JDK: jdk 6.0 beta2 (JDK 5.0 也可以)IDE: NetBeans 5.0 中文版
二、开发
1) 创建实体Entity类
1、地址类 Address :
/*
*Address.java
*/
packageorg.pisces.persist;
importjava.io.Serializable;
importjavax.persistence.Column;
importjavax.persistence.Entity;
importjavax.persistence.Id;
/**
*
*@authorkamhung
*/
@Entity
publicclassAddressimplementsSerializable{
//地址id,不能为空,必须唯一
@Id
@Column(name="addressid",unique=true,nullable=false)
privateintaddressid;
//城市,不能为空
@Column(name="city",nullable=false)
privateStringcity;
//街道,不能为空
@Column(name="street",nullable=false)
privateStringstreet;
//邮政编码,不能为空
@Column(name="zip",nullable=false)
privateStringzip;
publicAddress(){
}
publicAddress(intaddressid){
this.setAddressid(addressid);
}
publicintgetAddressid(){
returnthis.addressid;
}
publicvoidsetAddressid(intaddressid){
this.addressid=addressid;
}
publicStringgetCity(){
returnthis.city;
}
publicvoidsetCity(Stringcity){
this.city=city;
}
publicStringgetStreet(){
returnstreet;
}
publicvoidsetStreet(Stringstreet){
this.street=street;
}
publicStringgetZip(){
returnthis.zip;
}
publicvoidsetZip(Stringzip){
this.zip=zip;
}
@Override
publicinthashCode(){
returnthis.addressid;
}
@Override
publicbooleanequals(Objectobject){
if(!(objectinstanceofAddress))returnfalse;
finalAddressother=(Address)object;
returnthis.addressid==other.addressid;
}
@Override
publicStringtoString(){
return"Address[addressid="+getAddressid()+",city='"+getCity()+"',street='"+getStreet()+"',zip='"+getZip()+"']";
}
}
*Address.java
*/
packageorg.pisces.persist;
importjava.io.Serializable;
importjavax.persistence.Column;
importjavax.persistence.Entity;
importjavax.persistence.Id;
/**
*
*@authorkamhung
*/
@Entity
publicclassAddressimplementsSerializable{
//地址id,不能为空,必须唯一
@Id
@Column(name="addressid",unique=true,nullable=false)
privateintaddressid;
//城市,不能为空
@Column(name="city",nullable=false)
privateStringcity;
//街道,不能为空
@Column(name="street",nullable=false)
privateStringstreet;
//邮政编码,不能为空
@Column(name="zip",nullable=false)
privateStringzip;
publicAddress(){
}
publicAddress(intaddressid){
this.setAddressid(addressid);
}
publicintgetAddressid(){
returnthis.addressid;
}
publicvoidsetAddressid(intaddressid){
this.addressid=addressid;
}
publicStringgetCity(){
returnthis.city;
}
publicvoidsetCity(Stringcity){
this.city=city;
}
publicStringgetStreet(){
returnstreet;
}
publicvoidsetStreet(Stringstreet){
this.street=street;
}
publicStringgetZip(){
returnthis.zip;
}
publicvoidsetZip(Stringzip){
this.zip=zip;
}
@Override
publicinthashCode(){
returnthis.addressid;
}
@Override
publicbooleanequals(Objectobject){
if(!(objectinstanceofAddress))returnfalse;
finalAddressother=(Address)object;
returnthis.addressid==other.addressid;
}
@Override
publicStringtoString(){
return"Address[addressid="+getAddressid()+",city='"+getCity()+"',street='"+getStreet()+"',zip='"+getZip()+"']";
}
}
2、用户类 UserInfo:
/*
*UserInfo2.java
*/
packageorg.pisces.persist;
importjava.io.Serializable;
importjava.sql.Timestamp;
importjavax.persistence.Column;
importjavax.persistence.Entity;
importjavax.persistence.Id;
importjavax.persistence.JoinColumn;
importjavax.persistence.OneToOne;
importstaticjavax.persistence.CascadeType.*;
/**
*
*@authorkamhung
*/
@Entity
publicclassUserInfoimplementsSerializable{
//用户id,不能为空,必须唯一
@Id
@Column(name="userid",unique=true,nullable=false)
privateintuserid;
//用户名,不能为空
@Column(name="userName",nullable=false)
privateStringuserName;
//性别,不能为空
@Column(name="sex",nullable=false)
privateStringsex;
//出生日期,可以为空
@Column(name="birthday")
privateTimestampbirthday;
//地址,不能为空
//PERSIST表示更新、新增UserInfo数据时会同时更新、新增Address的数据
//REMOVE表示从数据库删除UserInfo会同时删除Address表中对应的数据
@OneToOne(cascade={PERSIST,REMOVE})
@JoinColumn(name="addressID",nullable=false)
privateAddressaddress;
publicUserInfo(){
}
publicUserInfo(intuserid){
this.setUserid(userid);
}
@Override
publicinthashCode(){
returnthis.getUserid();
}
@Override
publicbooleanequals(Objectobject){
if(!(objectinstanceofUserInfo))returnfalse;
finalUserInfoother=(UserInfo)object;
returnthis.userid==other.userid;
}
@Override
publicStringtoString(){
return"UserInfo[userid="+this.userid+",userName='"+userName+"',sex='"+sex
+"',birthday="+birthday+",address="+address+"]";
}
publicintgetUserid(){
returnuserid;
}
publicvoidsetUserid(intuserid){
this.userid=userid;
}
publicStringgetUserName(){
returnuserName;
}
publicvoidsetUserName(StringuserName){
this.userName=userName;
}
publicTimestampgetBirthday(){
returnbirthday;
}
publicvoidsetBirthday(Timestampbirthday){
this.birthday=birthday;
}
publicStringgetSex(){
returnsex;
}
publicvoidsetSex(Stringsex){
this.sex=sex;
}
publicAddressgetAddress(){
returnaddress;
}
publicvoidsetAddress(Addressaddress){
this.address=address;
}
}
*UserInfo2.java
*/
packageorg.pisces.persist;
importjava.io.Serializable;
importjava.sql.Timestamp;
importjavax.persistence.Column;
importjavax.persistence.Entity;
importjavax.persistence.Id;
importjavax.persistence.JoinColumn;
importjavax.persistence.OneToOne;
importstaticjavax.persistence.CascadeType.*;
/**
*
*@authorkamhung
*/
@Entity
publicclassUserInfoimplementsSerializable{
//用户id,不能为空,必须唯一
@Id
@Column(name="userid",unique=true,nullable=false)
privateintuserid;
//用户名,不能为空
@Column(name="userName",nullable=false)
privateStringuserName;
//性别,不能为空
@Column(name="sex",nullable=false)
privateStringsex;
//出生日期,可以为空
@Column(name="birthday")
privateTimestampbirthday;
//地址,不能为空
//PERSIST表示更新、新增UserInfo数据时会同时更新、新增Address的数据
//REMOVE表示从数据库删除UserInfo会同时删除Address表中对应的数据
@OneToOne(cascade={PERSIST,REMOVE})
@JoinColumn(name="addressID",nullable=false)
privateAddressaddress;
publicUserInfo(){
}
publicUserInfo(intuserid){
this.setUserid(userid);
}
@Override
publicinthashCode(){
returnthis.getUserid();
}
@Override
publicbooleanequals(Objectobject){
if(!(objectinstanceofUserInfo))returnfalse;
finalUserInfoother=(UserInfo)object;
returnthis.userid==other.userid;
}
@Override
publicStringtoString(){
return"UserInfo[userid="+this.userid+",userName='"+userName+"',sex='"+sex
+"',birthday="+birthday+",address="+address+"]";
}
publicintgetUserid(){
returnuserid;
}
publicvoidsetUserid(intuserid){
this.userid=userid;
}
publicStringgetUserName(){
returnuserName;
}
publicvoidsetUserName(StringuserName){
this.userName=userName;
}
publicTimestampgetBirthday(){
returnbirthday;
}
publicvoidsetBirthday(Timestampbirthday){
this.birthday=birthday;
}
publicStringgetSex(){
returnsex;
}
publicvoidsetSex(Stringsex){
this.sex=sex;
}
publicAddressgetAddress(){
returnaddress;
}
publicvoidsetAddress(Addressaddress){
this.address=address;
}
}
2) 创建配置文件persistence.xml
在项目src文件夹下创建一个META-INF文件夹(有就不用创建了), META-INF文件夹下建一个persistence.xml文件, 内容为:
<?xmlversion="1.0"encoding="UTF-8"?>
<persistenceversion="1.0"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/persistencehttp://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<!--transaction-type可选值有:JTA、RESOURCE_LOCAL;
在JavaEE环境下默认值为JTA,在JavaSE环境下默认值为RESOURCE_LOCAL;
如果值为JTA的话,则必须要指定<jta-data-source>的值-->
<persistence-unitname="piscesPU"transaction-type="RESOURCE_LOCAL">
<description>这是piscesPU持久化单元的一个简单描述</description>
<!--指明javax.persistence.spi.PersistenceProvider的实现类,一般来说该节点可以省略-->
<provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
<!--在JavaSE环境下必须定义所有的实体Entity类,也可以用<mapping-file>或<jar-file>节点代替-->
<class>org.pisces.persist.UserInfo</class>
<class>org.pisces.persist.Address</class>
<!--
//可以定义jndi资源代替properties节点中的数据库配置,
//但是在调用Persistence.createEntityManagerFactory方法前必须保证此资源已经注入程序中.
<jta-data-source>jdbc/persist</jta-data-source>
-->
<!--properties节点是用来定义各种JPA实现包所定义的属性配置-->
<!--下面列举的是toplink实现包中可以配置的部分属性-->
<properties>
<!--数据库连接配置,JDBC驱动-->
<propertyname="toplink.jdbc.driver"value="com.mysql.jdbc.Driver"/>
<persistenceversion="1.0"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/persistencehttp://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<!--transaction-type可选值有:JTA、RESOURCE_LOCAL;
在JavaEE环境下默认值为JTA,在JavaSE环境下默认值为RESOURCE_LOCAL;
如果值为JTA的话,则必须要指定<jta-data-source>的值-->
<persistence-unitname="piscesPU"transaction-type="RESOURCE_LOCAL">
<description>这是piscesPU持久化单元的一个简单描述</description>
<!--指明javax.persistence.spi.PersistenceProvider的实现类,一般来说该节点可以省略-->
<provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
<!--在JavaSE环境下必须定义所有的实体Entity类,也可以用<mapping-file>或<jar-file>节点代替-->
<class>org.pisces.persist.UserInfo</class>
<class>org.pisces.persist.Address</class>
<!--
//可以定义jndi资源代替properties节点中的数据库配置,
//但是在调用Persistence.createEntityManagerFactory方法前必须保证此资源已经注入程序中.
<jta-data-source>jdbc/persist</jta-data-source>
-->
<!--properties节点是用来定义各种JPA实现包所定义的属性配置-->
<!--下面列举的是toplink实现包中可以配置的部分属性-->
<properties>
<!--数据库连接配置,JDBC驱动-->
<propertyname="toplink.jdbc.driver"value="com.mysql.jdbc.Driver"/>
本文地址:http://www.45fan.com/a/question/71320.html