- 浏览: 499038 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (250)
- concurrent (11)
- io (1)
- CI (10)
- linux (57)
- windows (2)
- java (38)
- mac (4)
- eclipse (9)
- db (13)
- python (5)
- groovy (5)
- flex (7)
- hibernate (5)
- odb (8)
- netbeans (1)
- web (31)
- book (14)
- erlang (2)
- communication (2)
- virtualization (5)
- jUnit (0)
- jsf (1)
- perl (1)
- java jax-rs (5)
- Jenkins (2)
- Jenkins Plugin (3)
- android (2)
- git (1)
- big data (0)
- 试读 (1)
最新评论
-
yzzy4793:
讲的很清楚,明白
同步synchronized方法和代码块 -
aa51513:
中文乱码式硬伤
Jersey2.x对REST请求处理流程的分析 -
feiwomoshu1991:
...
同步synchronized方法和代码块 -
marshan:
启动失败的原因是加载的类版本冲突,因此你首先要保证依赖的版本和 ...
richfaces中facelet版本升级到2时的典型错误和解决办法 -
zhaohang6688:
请问我按照你的方式修改还是报错 错误信息还是这个 是为什么啊 ...
richfaces中facelet版本升级到2时的典型错误和解决办法
刚刚接触JPA2,写了个测试程序和大家分享。
环境:
server:JBoss6-M3
db:mysql
1.创建数据库 jpa
, 建表 user:
CREATE TABLE `user` ( `userid` int(11) NOT NULL auto_increment, `usercode` varchar(255) default NULL, `username` varchar(255) default NULL, `password` varchar(255) default NULL, `email` varchar(255) default NULL, `remark` varchar(255) default NULL, PRIMARY KEY (`userid`) ) TYPE=MyISAM; |
2.配置资源文件 mysql-ds.xml
放到 jboss deploy 目录下(比如 D:\server\jboss6m3\server\default\deploy
)
<?xml
version="1.0" encoding="UTF-8"?> <datasources> <local-tx-datasource> <jndi-name>jpa2 </jndi-name> <connection-url>jdbc:mysql://localhost:3306/jpa </connection-url> <driver-class>com.mysql.jdbc.Driver</driver-class> <user-name>root</user-name> <password>123456WSad!</password> <min-pool-size>5</min-pool-size> <max-pool-size>100</max-pool-size> <idle-timeout-minutes>15</idle-timeout-minutes> <check-valid-connection-sql>select count(*) from user</check-valid-connection-sql> <track-statements/> </local-tx-datasource> </datasources> |
3.配置 jpa2 的persistence文件 persistence.xml,该文件应放到 src/META-INF下,否则请使用ant,maven等工具编译到classes/META-INF下。
<?xml version="1.0" encoding="UTF-8"?>
<persistence
version="2.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/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd
">
<persistence-unit
name="JPA2
"
transaction-type="JTA">
<jta-data-source>java:jpa2
</jta-data-source>
<properties/>
</persistence-unit>
</persistence>
|
properties
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/> 正向工程时会用到:创建数据库和相关表
4.使用JPA2的工具,或者手动创建 User.java
package com.pojo;
import
java.io.Serializable;
import javax.persistence.Basic;
import
javax.persistence.Column;
import javax.persistence.Entity;
import
javax.persistence.GeneratedValue;
import
javax.persistence.GenerationType;
import javax.persistence.Id;
import
javax.persistence.NamedQueries;
import
javax.persistence.NamedQuery;
import javax.persistence.Table;
@Entity
@Table(name = "user
")
@NamedQueries(
{
@NamedQuery(name = "User.findAll", query = "SELECT u FROM
User u"),
@NamedQuery(name = "User.findByUserid", query =
"SELECT u FROM User u WHERE u.userid = :userid"),
@NamedQuery(name
= "User.findByUsercode", query = "SELECT u FROM User u WHERE u.usercode
= :usercode"),
@NamedQuery(name = "User.findByUsername",
query = "SELECT u FROM User u WHERE u.username = :username"),
@NamedQuery(name
= "User.findByPassword", query = "SELECT u FROM User u WHERE u.password
= :password"),
@NamedQuery(name = "User.findByEmail", query =
"SELECT u FROM User u WHERE u.email = :email"),
@NamedQuery(name
= "User.findByRemark", query = "SELECT u FROM User u WHERE u.remark =
:remark") })
public class User
implements Serializable {
private
static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy
= GenerationType.IDENTITY)
@Basic(optional
= false)
@Column(name =
"userid")
private Integer userid;
@Column(name = "usercode")
private
String usercode;
@Column(name =
"username")
private String username;
@Column(name = "password")
private
String password;
@Column(name = "email")
private
String email;
@Column(name = "remark")
private
String remark;
public User() {
}
public
User(Integer userid) {
this.userid = userid;
}
public
Integer getUserid() {
return userid;
}
public
void setUserid(Integer userid) {
this.userid = userid;
}
public
String getUsercode() {
return usercode;
}
public
void setUsercode(String usercode) {
this.usercode = usercode;
}
public
String getUsername() {
return username;
}
public
void setUsername(String username) {
this.username = username;
}
public
String getPassword() {
return password;
}
public
void setPassword(String password) {
this.password = password;
}
public
String getEmail() {
return email;
}
public
void setEmail(String email) {
this.email = email;
}
public
String getRemark() {
return remark;
}
public
void setRemark(String remark) {
this.remark = remark;
}
@Override
public
int hashCode() {
int hash = 0;
hash += (userid !=
null ? userid.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object
object) {
// TODO: Warning - this method won't work in the
case the id fields are
// not set
if (!(object
instanceof User)) {
return false;
}
User
other = (User) object;
if ((this.userid == null &&
other.userid != null)
|| (this.userid != null &&
!this.userid.equals(other.userid))) {
return false;
}
return
true;
}
@Override
public String
toString() {
return "com.pojo.User[userid=" + userid + "]";
}
}
|
5.创建访问数据库的session bean
package
com.ejb;
import com.pojo.User;
import
java.util.List;
import javax.ejb.Stateless;
import
javax.persistence.EntityManager;
import
javax.persistence.PersistenceContext;
import
javax.persistence.Query;
@Stateless
public
class Userdao {
@PersistenceContext(unitName
= "
JPA2
")
private
EntityManager em;
public void save(User entity) {
this.em.persist(entity);
}
public
void delete(User entity) {
try {
em.remove(em.merge(entity));
}
catch (Exception e) {
String s = e.getMessage();
System.out.print(s);
}
}
public
void update(User entity) {
em.merge(entity);
}
public
List<User> getAll() {
Query query =
em.createNamedQuery("User.findAll");
return
query.getResultList();
}
public User getById(int
id) {
return (User)
em.createNamedQuery("User.findByUserid").getSingleResult();
}
public
User getByUserCode(String usercode) {
Query query =
em.createNamedQuery("User.findByUsercode");
query.setParameter("usercode",
usercode);
try {
Object o =
query.getSingleResult();
return (User) o;
} catch
(Exception e) {// if result more than one, it will throw
//
exception.
String s = e.getMessage();
System.out.print(s);
}
return
null;
}
public User getByUserName(String
username) {
Query query =
em.createNamedQuery("User.findByUsername");
query.setParameter("username",
username);
return (User) query.getSingleResult();
}
}
|
6.创建测试使用的servlet
package com.servlet;
import
java.io.IOException;
import java.io.PrintWriter;
import
java.util.List;
import javax.ejb.EJB;
import
javax.servlet.ServletException;
import
javax.servlet.annotation.WebServlet;
import
javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
import
com.ejb.Userdao;
import com.pojo.User;
@WebServlet(name = "
TestServlet
", urlPatterns = {
"/TestServlet"
})
public class TestServlet extends
HttpServlet {
@EJB
private Userdao userDao;
protected void
processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String msg = "";
String para =
request.getParameter("method");
msg = "method=" +
para + " :\n";
if (para.equals("insert")) {
String username = request.getParameter("username");
String usercode = request.getParameter("usercode");
String password = request.getParameter("password");
String email = request.getParameter("email");
User user = new User();
user.setUsercode(usercode);
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
this.userDao.save(user);
msg +=
"successful insert :" + username;
} else if
(para.equals("update")) {
String username =
request.getParameter("username");
String usercode =
request.getParameter("usercode");
String password
= request.getParameter("password");
String email =
request.getParameter("email");
User user =
this.userDao.getByUserCode(usercode);
user.setUsercode(usercode);
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
this.userDao.update(user);
msg +=
"successful update :" + username;
} else if
(para.equals("delete")) {
String usercode =
request.getParameter("usercode");
User user =
this.userDao.getByUserCode(usercode);
if (user !=
null) {
this.userDao.delete(user);
}
msg += "successful remove :" +
user.getUsername();
} else if (para.equals("findall"))
{
List<User> list =
this.userDao.getAll();
for (User user : list) {
msg += "—>" + user.getUsername();
}
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet TestServlet</title>");
out.println("</head>");
out.println("<body>");
out.println(msg);
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
@Override
protected void
doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest
request, HttpServletResponse response)
throws
ServletException, IOException {
String mothed =
request.getParameter("method");
if
(mothed.equals("insert")) {
processRequest(request, response);
}
}
@Override
public String
getServletInfo() {
return "Short description";
}
}
|
7最后写一个测试用的 jsp
<%@page contentType="text/html"
pageEncoding="UTF-8"%>
<!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>JSP Page</title>
</head>
<body>
<a
href="http://localhost:8080/eboss/TestServlet
?method=insert
&usercode=zhangshan
&username=zhangsan
&password=1234
&email=zhangshan@gmail.com
">
insert test
</a>
<br/>
<a
href="http://localhost:8080/eboss/TestServlet?method=update&usercode=zhangshan&username=lisi&password=4321&email=lisi@gmail.com">
update test
</a>
<br/>
<a
href="http://localhost:8080/eboss/TestServlet?method=findall">
list test
</a>
<br/>
<a
href="http://localhost:8080/eboss/TestServlet?method=delete&usercode=zhangshan">
delete test
</a>
</body>
</html>
|
8. 别忘了把 db driver jar 放入 jboss lib 目录(比如 D:\server\jboss6m3\server\default\lib ,driver jar:mysql-connector-java-5.1.6-bin.jar )
9. 运行JBoss 访问 http://localhost:8080/eboss/
发表评论
-
Hibernate3.4 annotations 在Linux下作怪始末
2009-07-09 00:20 1466辛辛苦苦写的一个blog(如果你有兴趣可以自由下载:http: ... -
hibernatemanytoone的问题
2009-04-07 15:43 1053Data truncation: Data too long ... -
Hibernate 3.4中的两个问题
2009-03-29 21:34 1689很久没有用hibernate了,由于自己要做个小东西,想了想, ... -
hibernate中 查询表名和字段名
2008-04-24 11:58 4336/** * hibernate 实体、属性查询表名、字段名工具 ...
相关推荐
4. JPA(Java Persistence API)集成:EJB 3.x集成了JPA,使得持久化操作更加简单,通过`@Entity`,`@Table`等注解可以轻松管理数据库模型。 5. 更强的可移植性:EJB 3.x遵循Java EE规范,保证了代码在不同应用...
JBoss不仅支持各种J2EE组件,如Servlet、JSP、EJB等,还包含了诸如JMS(Java消息服务)、JPA(Java持久化API)和JTA(Java事务API)等企业级功能。使用JBoss,开发者可以在本地或云端部署和运行J2EE应用。 创建J2EE...
通过这个图式教学,你将学会如何使用JBoss Studio高效地开发Seam项目,理解Seam框架的核心概念,包括组件管理、JSF集成、CDI依赖注入和JPA持久化等。这将有助于你在实际工作中构建稳定、可维护的Java EE企业级应用。
2 JBoss Seam 简介......................................................................................................................................................................... 11 Chapter 1...
5. **Deployment on EAP**:Enterprise Application Platform,如 Red Hat JBoss EAP,是一个企业级的服务器,提供了运行和管理 Java 应用程序的环境。部署 `simple-jpa-webapp` 到 EAP 需要配置应用服务器,包括...
6. **定义JPA实体**:创建Java类作为JPA实体,使用`@Entity`注解标记,并通过`@Table`指定对应的数据库表。同时,使用`@Id`注解定义主键。 ```java import javax.persistence.Entity; import javax.persistence....
《Expert One-on-One J2EE Design and Development》是Java领域中一本重要的技术专著,主要关注J2EE(Java 2 Platform, Enterprise Edition)平台上的设计与开发实践。这本书由Ronald Miels和Peter Eberhardt合著,...
"工具"标签可能意味着书中讨论了与J2EE开发相关的工具,例如IDE(集成开发环境)如Eclipse或NetBeans,构建工具如Maven或Ant,以及部署工具和服务器,如Tomcat、WebLogic或JBoss。掌握这些工具的使用能够提高开发...
JDK的java.transaction模块已通过org.jboss.spec.javax.transaction:jboss-transaction-api_1.2_spec:2.0.0.Alpha1升级,该模型添加了所有JTA类型(XA包与Java冲突的除外) .sql模块) hibernate-jpa-2.1-api-...
版本5.0是其发展过程中的一个重要里程碑,提供了更为成熟的企业级服务,如EJB(Enterprise JavaBeans)、JPA(Java Persistence API)、JSF(JavaServer Faces)等,极大地简化了复杂应用的开发过程。 ### ...
Seam框架是JBoss的一个组成部分,它是一个用于构建企业级应用程序的开源框架,专注于简化Java EE应用程序的开发流程。Seam将JSF、EJB 3.0、JPA、JSTL等技术整合在一起,提供了丰富的组件库和实用工具,使开发者能够...
- Java EE 6是Java平台企业版的一个版本,它包含了一系列用于构建分布式、多层企业级应用的技术,如Servlet、JSP、EJB、JPA、JSF等。 - 教程可能涵盖了Web服务、数据访问、事务管理、安全管理等多个方面的内容,...
JBoss Tools on Eclipse 3.6 (Helios) 的新版,对于使用JBoss平台的开发者来说是个好消息,它加强了Eclipse IDE对Java EE应用的支持。 Apache CouchDB 1.0.0的发布,标志着这个NoSQL数据库的重要里程碑,为分布式...
WildFly(原名JBoss AS)是由Red Hat公司开发的一款开源应用服务器,它支持Java EE规范,为企业级Java应用程序提供运行环境。 【描述】中的"openshiftcoding-wildflycookbook"项目是一个针对OpenShift Online的演示...
- **JBoss/WildFly**:这是一个全功能的企业级应用服务器,支持EJB、JMS、JPA等技术。 - **WebLogic**:由Oracle公司开发的一款高性能、高可用性的商业应用服务器。 - **WebSphere**:由IBM公司开发的一款企业级应用...