国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Maven 版 JPA 最佳實踐

2019-11-14 21:58:35
字體:
來源:轉載
供稿:網友
Maven 版 JPA 最佳實踐項目結構圖

snap0596

數據庫環境
  • 數據庫:MySQL
  • 版本:5.x
  • 數據庫名:jpa-demo
  • 用戶名密碼:root/1234
代碼清單 1:數據庫腳本:
/*Navicat MySQL Data TransferSource Server         : localhostSource Server Version : 50525Source Host           : localhost:3306Source Database       : jpa-demoTarget Server Type    : MYSQLTarget Server Version : 50525File Encoding         : 65001Date: 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');
源代碼代碼清單 2:pom.xml
<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>
代碼清單 3: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="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>
代碼清單 4:Address.java
package com.coderdream.model;import java.io.Serializable;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.Id;@Entitypublic 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;}@Overridepublic int hashCode() {return this.addressid;}@Overridepublic boolean equals(Object object) {if (!(object instanceof Address))return false;final Address other = (Address) object;return this.addressid == other.addressid;}@Overridepublic String toString() {return "Address[addressid=" + getAddressid() + ", city='" + getCity() + "', street='" + getStreet() + "', zip='" + getZip() + "";}}
代碼清單 5:UserInfo.java
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.*;@Entitypublic 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);}@Overridepublic int hashCode() {return this.getUserid();}@Overridepublic boolean equals(Object object) {if (!(object instanceof UserInfo))return false;final UserInfo other = (UserInfo) object;return this.userid == other.userid;}@Overridepublic 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;}}
代碼清單 6:SimpleService.java
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/8181849

參考文檔
  1. 在Java SE環境下使用JPA1.0(1)

  2. Toplink JPA簡介


上一篇:XML基礎知識

下一篇:FileDescriptor

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阿坝县| 来凤县| 洛川县| 巴林左旗| 榆树市| 丰县| 东宁县| 海兴县| 资源县| 五原县| 平原县| 河南省| 化州市| 房产| 左云县| 封丘县| 武山县| 孙吴县| 连城县| 石家庄市| 汉源县| 高密市| 呼图壁县| 阳泉市| 大港区| 定安县| 贵南县| 乌兰县| 台中县| 沈丘县| 龙胜| 兴义市| 高要市| 秦皇岛市| 泾阳县| 恩施市| 临洮县| 中超| 鄂托克前旗| 青川县| 西宁市|