posts - 1,  comments - 1,  trackbacks - 0
这里我用的是openJPA
persistence.xml文件的配置
 1 <persistence-unit name="test">
 2   <class>cn.is.test.Test</class>
 3 
 4   <properties>
 5     <property name="openjpa.ConnectionURL" value="jdbc:mysql://localhost:3306/test" />
 6     <property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver" />
 7     <property name="openjpa.ConnectionUserName" value="root" />
 8     <property name="openjpa.ConnectionPassword" value="root" />
 9   </properties>
10 </persistence-unit>

这里有个问题,我一般用mysql驱动的org.gjt.mm.mysql.Driver这个驱动类,但是在这里,运行的时候报驱动类或着连接URL错误


下面的是实体类
 1 package cn.is.test;
 2 
 3 import java.io.Serializable;
 4 import javax.persistence.Entity;
 5 import javax.persistence.Id;
 6 
 7 @Entity
 8 public class Test implements Serializable {
 9   @Id
10   private String id;
11 
12   private String userName;
13 
14   private String password;
15 
16   private String sex;
17 
18   private static final long serialVersionUID = 1L;
19 
20   public Test() {
21     super();
22   }
23 
24   public String getId() {
25     return this.id;
26   }
27 
28   public void setId(String id) {
29     this.id = id;
30   }
31 
32   public String getUserName() {
33     return this.userName;
34   }
35 
36   public void setUserName(String username) {
37     this.userName = username;
38   }
39 
40   public String getPassword() {
41     return this.password;
42   }
43 
44   public void setPassword(String password) {
45     this.password = password;
46   }
47 
48   public String getSex() {
49     return this.sex;
50   }
51 
52   public void setSex(String sex) {
53     this.sex = sex;
54   }
55 
56 
57 
58 }
59 

下来的是测试代码:

 1 EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");
 2 EntityManager em = factory.createEntityManager();
 3 Test test = new Test();
 4 test.setId(UUID.randomUUID().toString());
 5 test.setSex("");
 6 test.setUserName("Innate");
 7 test.setPassword("solitary");
 8 
 9 em.getTransaction().begin();
10 
11 em.persist(test);
12 
13 em.getTransaction().commit();
14 
15 em.close();
16 
17 em = factory.createEntityManager();
18 
19 Query query = em.createQuery("select t from Test t");
20 List<Test> testList = query.getResultList();
21 
22 for (Test _test : testList) {
23   System.out.println(_test.getUserName());
24 }
25 
26 em.close();
27 factory.close();

posted on 2010-04-03 16:01 天独 阅读(295) 评论(0)  编辑  收藏 所属分类: Java

只有注册用户登录后才能发表评论。


网站导航: