日期:2014-05-16  浏览次数:20556 次

JPA+mysql+servlet实现的连接操作数据库的小例子

persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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_1_0.xsd" version="1.0">
    
	<persistence-unit name="mysql" transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
  		
  		<jta-data-source>java:comp/env/jdbc/mysql</jta-data-source>
  		
  		<class>com.chinasoft.database2.Persion</class>
 
  		<properties>
			<property name="hibernate.show_sql" value="true"></property>
	  	</properties>
	</persistence-unit>
  
</persistence>

?tomcat中server.xml配置:

  <Context path="/DatabaseTest" docBase="/DatabaseTest"  reloadable="false" crossContext="true">		 
		<Resource name="jdbc/mysql"   auth="Container"  type="javax.sql.DataSource"  
		maxActive="5"   maxIdle="2"   maxWait="10000"   removeAbandoned="true" removeAbandonedTimeout="60" logAbandoned="true" 
		driverClassName="com.mysql.jdbc.Driver" 
		url="jdbc:mysql://localhost/lpm?user=root&amp;password=" /> 
 </Context>

?建一个实体Persion类:

package com.chinasoft.database2;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="persion")
public class Persion {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private java.lang.Long userid;
    private java.lang.String name;
   
   
	public java.lang.Long getUserid() {
		return userid;
	}
	public void setUserid(java.lang.Long userid) {
		this.userid = userid;
	}
	public java.lang.String getName() {
		return name;
	}
	public void setName(java.lang.String name) {
		this.name = name;
	}
	
}

?建一个servlet类:

public class Start extends HttpServlet {

	?public void doGet(HttpServletRequest request, HttpServletResponse response)
???throws ServletException, IOException {
?? EntityManagerFactory entityfactory = null;
?? EntityTransaction? t=null;
?? EntityManager em=null;
??try{
???entityfactory = Persistence.createEntityManagerFactory("mysql");
???em=entityfactory.createEntityManager();
???
???Query query=em.createQuery("from Persion");
???List list=query.getResultList();
???Iterator iter=list.iterator();
???while(iter.hasNext()){
????Persion persion=(Persion) iter.next();
????System.out.println(persion.getName());
???}
???
???
????? t=em.getTransaction();
???t.begin();
???Persion p=new Persion();
???p.setName("abc");
???em.persist(p);
???t.commit();
??}catch(Exception e){
???e.printStackTrace();
???t.rollback();
??}
??em.close();
??entityfactory.close();
?}

}

?