/* Navicat MySQL Data Transfer Source Server : localhost Source Server Version : 50525 Source Host : localhost:3306 Source Database : jpa-demo Target Server Type : MYSQL Target Server Version : 50525 File Encoding : 65001 Date: 2014-11-20 20:09:27 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `address` -- ---------------------------- DROP TABLE IF EXISTS `address`; CREATE TABLE `address` ( `addressID` int(11) NOT NULL, `city` varchar(55) NOT NULL, `street` varchar(55) NOT NULL, `zip` varchar(8) NOT NULL, PRIMARY KEY (`addressID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of address -- ---------------------------- INSERT INTO `address` VALUES ('1', '深圳', '阪田市場', '518001'); INSERT INTO `address` VALUES ('2', '深圳', '阪田路口', '518002'); INSERT INTO `address` VALUES ('3', '深圳', '四季花城', '518003'); -- ---------------------------- -- Table structure for `userinfo` -- ---------------------------- DROP TABLE IF EXISTS `userinfo`; CREATE TABLE `userinfo` ( `userID` int(11) NOT NULL, `username` varchar(20) NOT NULL, `birthday` datetime DEFAULT NULL, `sex` varchar(8) NOT NULL, `addressID` int(11) NOT NULL, PRIMARY KEY (`userID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of userinfo -- ---------------------------- INSERT INTO `userinfo` VALUES ('1', '張金雄', null, 'male', '1'); INSERT INTO `userinfo` VALUES ('2', '李某某', null, 'male', '2'); INSERT INTO `userinfo` VALUES ('3', '王某某', '2006-08-10 00:00:00', 'female', '3'); INSERT INTO `userinfo` VALUES ('4', '陳某某', '2006-08-12 00:00:00', 'male', '3');
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.coderdream</groupId> <artifactId>jpa-demo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>jpa-demo Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <junit.version>4.11</junit.version> <mysql.version>5.1.17</mysql.version> <slf.version>1.7.5</slf.version> <toplink.essentials.version>2.1-60f</toplink.essentials.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>toplink.essentials</groupId> <artifactId>toplink-essentials</artifactId> <version>${toplink.essentials.version}</version> </dependency> <dependency> <groupId>toplink.essentials</groupId> <artifactId>toplink-essentials-agent</artifactId> <version>${toplink.essentials.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> </dependencies> <build> <finalName>jpa-demo</finalName> </build> </project>
<?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="piscesPU" transaction-type="RESOURCE_LOCAL"> <provider> oracle.toplink.essentials.PersistenceProvider </provider> <class>com.coderdream.model.UserInfo</class> <class>com.coderdream.model.Address</class> <properties> <!-- 數據庫鏈接配置, JDBC驅動 --> <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver" /> <!-- 數據庫鏈接配置,URL --> <property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/jpa-demo" /> <!-- 數據庫鏈接配置, 用戶名 --> <property name="toplink.jdbc.user" value="root" /> <!-- 數據庫鏈接配置, 密碼 --> <property name="toplink.jdbc.password" value="1234" /> </properties> </persistence-unit> </persistence>
package com.coderdream.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Address implements Serializable { // 地址id, 不能爲空, 必須惟一 @Id @Column(name = "addressid", unique = true, nullable = false) private int addressid; // 城市, 不能爲空 @Column(name = "city", nullable = false) private String city; // 街道, 不能爲空 @Column(name = "street", nullable = false) private String street; // 郵政編碼, 不能爲空 @Column(name = "zip", nullable = false) private String zip; public Address() { } public Address(int addressid) { this.setAddressid(addressid); } public int getAddressid() { return this.addressid; } public void setAddressid(int addressid) { this.addressid = addressid; } public String getCity() { return this.city; } public void setCity(String city) { this.city = city; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getZip() { return this.zip; } public void setZip(String zip) { this.zip = zip; } @Override public int hashCode() { return this.addressid; } @Override public boolean equals(Object object) { if (!(object instanceof Address)) return false; final Address other = (Address) object; return this.addressid == other.addressid; } @Override public String toString() { return "Address[addressid=" + getAddressid() + ", city='" + getCity() + "', street='" + getStreet() + "', zip='" + getZip() + ""; } }
package com.coderdream.model; import java.io.Serializable; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import static javax.persistence.CascadeType.*; @Entity public class UserInfo implements Serializable { // 用戶id, 不能爲空, 必須惟一 @Id @Column(name = "userid", unique = true, nullable = false) private int userid; // 用戶名, 不能爲空 @Column(name = "userName", nullable = false) private String userName; // 性別, 不能爲空 @Column(name = "sex", nullable = false) private String sex; // 出生日期, 能夠爲空 @Column(name = "birthday") private Timestamp birthday; // 地址, 不能爲空 // PERSIST 表示更新、新增UserInfo數據時會同時更新、新增Address的數據 // REMOVE 表示從數據庫刪除UserInfo會同時刪除Address表中對應的數據 @OneToOne(cascade = { PERSIST, REMOVE }) @JoinColumn(name = "addressID", nullable = false) private Address address; public UserInfo() { } public UserInfo(int userid) { this.setUserid(userid); } @Override public int hashCode() { return this.getUserid(); } @Override public boolean equals(Object object) { if (!(object instanceof UserInfo)) return false; final UserInfo other = (UserInfo) object; return this.userid == other.userid; } @Override public String toString() { return "UserInfo[userid=" + this.userid + ", userName='" + userName + "', sex='" + sex + "', birthday=" + birthday + ", address=" + address + ""; } public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Timestamp getBirthday() { return birthday; } public void setBirthday(Timestamp birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
package com.coderdream.service; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.coderdream.model.Address; import com.coderdream.model.UserInfo; public class SimpleService { /** * 刪除用戶id=6的數據 */ public static void delete() { final EntityManagerFactory emf = Persistence.createEntityManagerFactory("piscesPU"); final EntityManager em = emf.createEntityManager(); // 找不到數據的話這裏會拋異常 UserInfo info = em.find(UserInfo.class, 6); try { em.getTransaction().begin(); em.remove(info); em.getTransaction().commit(); } finally { em.close(); } } /** * 修改用戶id=6的數據 */ public static void update() { final EntityManagerFactory emf = Persistence.createEntityManagerFactory("piscesPU"); final EntityManager em = emf.createEntityManager(); // 找不到數據的話這裏會拋異常 UserInfo info = em.find(UserInfo.class, 6); info.setUserName("哈哈"); info.getAddress().setStreet("阪田2"); try { em.getTransaction().begin(); // 自動將info更新到數據庫 em.getTransaction().commit(); } finally { em.close(); } } /** * 查詢全部用戶數據 */ public static void query() { final EntityManagerFactory emf = Persistence.createEntityManagerFactory("piscesPU"); long s = System.currentTimeMillis(); // 數據庫鏈接失敗這裏會拋出異常 final EntityManager em = emf.createEntityManager(); long e = System.currentTimeMillis(); System.out.println("鏈接數據庫耗時: " + (e - s) + "毫秒"); // 獲取數據 @SuppressWarnings("unchecked") List<UserInfo> list = em.createQuery("SELECT a FROM UserInfo a").getResultList(); int i = 0; for (UserInfo info : list) { System.out.println("第" + (++i) + "個值爲: " + info); } em.close(); } /** * 建立用戶id=6的一條數據, 地址id=6 */ public static void create() { final EntityManagerFactory emf = Persistence.createEntityManagerFactory("piscesPU"); final EntityManager em = emf.createEntityManager(); UserInfo info = new UserInfo(6); info.setSex("male"); info.setUserName("張某某"); info.setBirthday(new java.sql.Timestamp(System.currentTimeMillis())); Address naddr = new Address(6); naddr.setCity("深圳"); naddr.setStreet("阪田"); naddr.setZip("518000"); info.setAddress(naddr); try { em.getTransaction().begin(); em.persist(info); em.getTransaction().commit(); } finally { em.close(); } } /** * 主函數 */ public static void main(String[] args) throws Throwable { SimpleService.query(); SimpleService.create(); System.out.println("新增一條數據後進行查詢"); SimpleService.query(); SimpleService.update(); System.out.println("修改一條數據後進行查詢"); SimpleService.query(); SimpleService.delete(); System.out.println("刪除一條數據後進行查詢"); SimpleService.query(); } }
[TopLink Info]: 2014.11.20 08:24:08.134--ServerSession(1112823384)--TopLink, version: Oracle TopLink Essentials - 2.1 (Build 60f (01/07/2009)) [TopLink Info]: 2014.11.20 08:24:08.822--ServerSession(1112823384)--file:/E:/E_441_64/workspace/jpa-demo/target/classes/-piscesPU login successful 鏈接數據庫耗時: 1264毫秒 第1個值爲: UserInfo[userid=1, userName='張金雄', sex='male', birthday=null, address=Address[addressid=1, city='深圳', street='阪田市場', zip='518001 第2個值爲: UserInfo[userid=2, userName='李某某', sex='male', birthday=null, address=Address[addressid=2, city='深圳', street='阪田路口', zip='518002 第3個值爲: UserInfo[userid=3, userName='王某某', sex='female', birthday=2006-08-10 00:00:00.0, address=Address[addressid=3, city='深圳', street='四季花城', zip='518003 第4個值爲: UserInfo[userid=4, userName='陳某某', sex='male', birthday=2006-08-12 00:00:00.0, address=Address[addressid=3, city='深圳', street='四季花城', zip='518003 新增一條數據後進行查詢 鏈接數據庫耗時: 0毫秒 第1個值爲: UserInfo[userid=1, userName='張金雄', sex='male', birthday=null, address=Address[addressid=1, city='深圳', street='阪田市場', zip='518001 第2個值爲: UserInfo[userid=2, userName='李某某', sex='male', birthday=null, address=Address[addressid=2, city='深圳', street='阪田路口', zip='518002 第3個值爲: UserInfo[userid=3, userName='王某某', sex='female', birthday=2006-08-10 00:00:00.0, address=Address[addressid=3, city='深圳', street='四季花城', zip='518003 第4個值爲: UserInfo[userid=4, userName='陳某某', sex='male', birthday=2006-08-12 00:00:00.0, address=Address[addressid=3, city='深圳', street='四季花城', zip='518003 第5個值爲: UserInfo[userid=6, userName='張某某', sex='male', birthday=2014-11-20 20:24:09.102, address=Address[addressid=6, city='深圳', street='阪田', zip='518000 修改一條數據後進行查詢 鏈接數據庫耗時: 0毫秒 第1個值爲: UserInfo[userid=1, userName='張金雄', sex='male', birthday=null, address=Address[addressid=1, city='深圳', street='阪田市場', zip='518001 第2個值爲: UserInfo[userid=2, userName='李某某', sex='male', birthday=null, address=Address[addressid=2, city='深圳', street='阪田路口', zip='518002 第3個值爲: UserInfo[userid=3, userName='王某某', sex='female', birthday=2006-08-10 00:00:00.0, address=Address[addressid=3, city='深圳', street='四季花城', zip='518003 第4個值爲: UserInfo[userid=4, userName='陳某某', sex='male', birthday=2006-08-12 00:00:00.0, address=Address[addressid=3, city='深圳', street='四季花城', zip='518003 第5個值爲: UserInfo[userid=6, userName='哈哈', sex='male', birthday=2014-11-20 20:24:09.102, address=Address[addressid=6, city='深圳', street='阪田2', zip='518000 刪除一條數據後進行查詢 鏈接數據庫耗時: 0毫秒 第1個值爲: UserInfo[userid=1, userName='張金雄', sex='male', birthday=null, address=Address[addressid=1, city='深圳', street='阪田市場', zip='518001 第2個值爲: UserInfo[userid=2, userName='李某某', sex='male', birthday=null, address=Address[addressid=2, city='深圳', street='阪田路口', zip='518002 第3個值爲: UserInfo[userid=3, userName='王某某', sex='female', birthday=2006-08-10 00:00:00.0, address=Address[addressid=3, city='深圳', street='四季花城', zip='518003 第4個值爲: UserInfo[userid=4, userName='陳某某', sex='male', birthday=2006-08-12 00:00:00.0, address=Address[addressid=3, city='深圳', street='四季花城', zip='518003
下載地址:http://download.csdn.net/detail/xuxiheng/8181849html
Toplink JPA簡介mysql