刚刚接触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"/> 正向工程时会用到:创建数据库和相关表
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 + "]";
}
}
|
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();
}
}
|
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";
}
}
|
<%@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 protected] ">
insert test
</a>
<br/>
<a href="http://localhost:8080/eboss/TestServlet?method=update&usercode=zhangshan&username=lisi&password=4321&[email protected]">
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>
|