Home Database Mysql Tutorial JPA初体验_MySQL

JPA初体验_MySQL

Jun 01, 2016 pm 01:49 PM
download

bitsCN.com

  JPA,一套相当优秀的持久化规范,开始体验。


 

  1、我使用Hibernate对JPA提供的实现,下载hibernate-release-4.1.1.Final.zip。解压。

  在hibernate-release-4.1.1.Final/lib目录下有四个存放jar包的目录,其中

   hibernate-release-4.1.1.Final/lib/jpa                   存放hibernate对JPA提供实现的jar

   hibernate-release-4.1.1.Final/lib/required            存放hibernate开发所需jar

  这两个目录下的所有jar是我们体验JPA所必需的。

 


 

  2、新建一个Java Project。

  2.1 导入hibernate-release-4.1.1.Final/lib/jpa目录和hibernate-release-4.1.1.Final/lib/required目录下得所有jar

  2.2 在项目的classpath路径下建立META-INF目录

        在META-INF目录下建立persistence.xml文件

    

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <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  5             http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> 6              7     <!-- 为持久化单元取名为 myJPA --> 8     <persistence-unit name="myJPA" transaction-type="RESOURCE_LOCAL"> 9         <properties>10             <!--配置Hibernate方言 -->11             <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"></property>12             <!--配置数据库驱动 -->13             <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"></property>14             <!--配置数据库用户名 -->15             <property name="hibernate.connection.username" value="root"></property>16             <!--配置数据库密码 -->17             <property name="hibernate.connection.password" value="root"></property>18             <!--配置数据库url -->19             <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/jpa?useUnicode=true&characterEncoding=UTF-8"></property>20             <!--设置外连接抓取树的最大深度 -->21             <property name="hibernate.max_fetch_depth" value="3"></property>22             <!--自动输出schema创建DDL语句 -->23             <property name="hibernate.hbm2ddl.auto" value="update"></property>    24         </properties>25     </persistence-unit>26             27 </persistence>
Copy after login

  用的是mysql,请建立一个名叫jpa的数据库。无需手动建表,执行测试的时候会自动建表。

 


 

  3、项目视图如下:

  

 


 

  4、编写实体类。

  

 1 package com.cndatacom.jpa.entity; 2  3 import javax.persistence.Column; 4 import javax.persistence.Entity; 5 import javax.persistence.GeneratedValue; 6 import javax.persistence.Id; 7 import javax.persistence.Table; 8  9 @Entity10 @Table(name="t_user")11 public class User {12     13     /**14      * 主键15      */16     @Id17     @GeneratedValue18     private Long id;19     20     /**21      * 名字22      */23     @Column(name="name")24     private String name;25     26     /**27      * 密码28      */29     @Column(name="password")30     private String password;31 32     public Long getId() {33         return id;34     }35 36     public void setId(Long id) {37         this.id = id;38     }39 40     public String getName() {41         return name;42     }43 44     public void setName(String name) {45         this.name = name;46     }47 48     public String getPassword() {49         return password;50     }51 52     public void setPassword(String password) {53         this.password = password;54     }55     56 }
Copy after login


5、编写测试类。

  

 1 package com.cndatacom.jpa.test; 2  3 import javax.persistence.EntityManager; 4 import javax.persistence.EntityManagerFactory; 5 import javax.persistence.Persistence; 6  7 import org.junit.After; 8 import org.junit.Before; 9 import org.junit.Test;10 11 import com.cndatacom.jpa.entity.User;12 13 14 public class TestJPA {15     16     EntityManagerFactory emf = null;17     18     @Before19     public void before() {20         //根据在persistence.xml中配置的persistence-unit name 创建EntityManagerFactory21         emf = Persistence.createEntityManagerFactory("myJPA");22     }23     24     /**25      * 添加用户26      */27     @Test28     public void addUser() {29         30         //创建一个用户31         User user = new User();32         user.setName("叶开");33         user.setPassword("yekai");34         35         //创建实体管理器对象36         EntityManager em = emf.createEntityManager();37         //开启事务38         em.getTransaction().begin();39         //持久化对象40         em.persist(user);41         //提交事务42         em.getTransaction().commit();43         //关闭EntityManager44         em.close();45     }46     47     /**48      * 修改用户49      */50     @Test51     public void modifyUser() {52         EntityManager em = emf.createEntityManager();53         em.getTransaction().begin();54         //查找id为1的User55         User user = em.find(User.class, 1L);//User 的主键id为Long型56         user.setName("李坏");57         //进行更新58         em.merge(user);59         em.getTransaction().commit();60         em.close();61     }62     63     /**64      * 删除用户65      */66     @Test67     public void deleteUser() {68         EntityManager em = emf.createEntityManager();69         em.getTransaction().begin();70         //查找id为1的User71         User user = em.find(User.class, 1L);//User 的主键id为Long型72         //进行删除73         em.remove(user);74         em.getTransaction().commit();75         em.close();76     }77     78     /**79      * 关闭EntityManagerFactory80      */81     @After82     public void after() {83         if(null != emf) {84             emf.close();85         }86     }87 88 }
Copy after login

 


 

  6、一些说明。

  @Entity 将领域标注为一个实体,表示要保存到数据库中。

  @Table 指定在数据库中对应的表名

  @Id 对应的属性是表的主键

  @GeneratedValue 主键的产生策略,这里表示使用默认的GenerationType.AUTO

  @Column 属性对应数据库表中的列,name指定列名,不写name的话,属性名和列名一致。

  

   

  

bitsCN.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use magnet links How to use magnet links Feb 18, 2024 am 10:02 AM

Magnet link is a link method for downloading resources, which is more convenient and efficient than traditional download methods. Magnet links allow you to download resources in a peer-to-peer manner without relying on an intermediary server. This article will introduce how to use magnet links and what to pay attention to. 1. What is a magnet link? A magnet link is a download method based on the P2P (Peer-to-Peer) protocol. Through magnet links, users can directly connect to the publisher of the resource to complete resource sharing and downloading. Compared with traditional downloading methods, magnetic

How to download episodes of Hongguo short drama How to download episodes of Hongguo short drama Mar 11, 2024 pm 09:16 PM

Hongguo Short Play is not only a platform for watching short plays, but also a treasure trove of rich content, including novels and other exciting content. This is undoubtedly a huge surprise for many users who love reading. However, many users still don’t know how to download and watch these novels in Hongguo Short Play. In the following, the editor of this website will provide you with detailed downloading steps. I hope it can help everyone in need. Partners. How to download and watch the Hongguo short play? The answer: [Hongguo short play] - [Audio book] - [Article] - [Download]. Specific steps: 1. First open the Hongguo Short Drama software, enter the homepage and click the [Listen to Books] button at the top of the page; 2. Then on the novel page we can see a lot of article content, here

What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? Mar 19, 2024 pm 02:00 PM

When you log in to someone else's steam account on your computer, and that other person's account happens to have wallpaper software, steam will automatically download the wallpapers subscribed to the other person's account after switching back to your own account. Users can solve this problem by turning off steam cloud synchronization. What to do if wallpaperengine downloads other people's wallpapers after logging into another account 1. Log in to your own steam account, find cloud synchronization in settings, and turn off steam cloud synchronization. 2. Log in to someone else's Steam account you logged in before, open the Wallpaper Creative Workshop, find the subscription content, and then cancel all subscriptions. (In case you cannot find the wallpaper in the future, you can collect it first and then cancel the subscription) 3. Switch back to your own steam

How to download links starting with 115://? Download method introduction How to download links starting with 115://? Download method introduction Mar 14, 2024 am 11:58 AM

Recently, many users have been asking the editor, how to download links starting with 115://? If you want to download links starting with 115://, you need to use the 115 browser. After you download the 115 browser, let's take a look at the download tutorial compiled by the editor below. Introduction to how to download links starting with 115:// 1. Log in to 115.com, download and install the 115 browser. 2. Enter: chrome://extensions/ in the 115 browser address bar, enter the extension center, search for Tampermonkey, and install the corresponding plug-in. 3. Enter in the address bar of 115 browser: Grease Monkey Script: https://greasyfork.org/en/

How to download files from 123 cloud disk How to download files from 123 cloud disk Feb 23, 2024 pm 08:58 PM

123 cloud disk can download many files, so how to download files specifically? Users can select the file they want to download and click to download, or right-click the file and select download. This introduction to the method of downloading files from 123 cloud disk can tell you how to download it specifically. Friends who don’t know much about it should hurry up and take a look! How to download files from 123 cloud disk 1. First open the software, click on the software that needs to be downloaded, and then there will be a download button on it. 2. Or right-click the software and you can see the download button in the list. 3. There will be a download window, select the location to download. 4. After selecting, click Download to download these files.

Introduction to how to download and install the superpeople game Introduction to how to download and install the superpeople game Mar 30, 2024 pm 04:01 PM

The superpeople game can be downloaded through the steam client. The size of this game is about 28G. It usually takes one and a half hours to download and install. Here is a specific download and installation tutorial for you! New method to apply for global closed testing 1) Search for "SUPERPEOPLE" in the Steam store (steam client download) 2) Click "Request access to SUPERPEOPLE closed testing" at the bottom of the "SUPERPEOPLE" store page 3) After clicking the request access button, The "SUPERPEOPLECBT" game can be confirmed in the Steam library 4) Click the install button in "SUPERPEOPLECBT" and download

How to download Quark network disk to local? How to save files downloaded from Quark Network Disk back to the local computer How to download Quark network disk to local? How to save files downloaded from Quark Network Disk back to the local computer Mar 13, 2024 pm 08:31 PM

Many users need to download files when using Quark Network Disk, but we want to save them locally, so how to set this up? Let this site introduce to users in detail how to save files downloaded from Quark Network Disk back to the local computer. How to save files downloaded from Quark network disk back to your local computer 1. Open Quark, log in to your account, and click the list icon. 2. After clicking the icon, select the network disk. 3. After entering Quark Network Disk, click My Files. 4. After entering My Files, select the file you want to download and click the three-dot icon. 5. Check the file you want to download and click Download.

How to download videos from a video account 'Must-see: A simple way to save videos from a video account' How to download videos from a video account 'Must-see: A simple way to save videos from a video account' Feb 06, 2024 pm 06:42 PM

Now more and more people are starting to play video accounts. Video accounts are also a short video platform where they can share their daily life and make money through video accounts. Recently, I saw some friends asking why the videos from the WeChat video account were not downloaded. Yang Shuaikang went to try it, and there was indeed no download button, so he could only extract the video through other means. Today Yang Shuaikang will share with you a stupid Method, come and take a look. How to extract videos from WeChat video accounts 1. Open our computer version of WeChat and find [Video Account] on the left; 2. Find the video you want to download through search; 3. Finally, use the screen recording tool to adjust the size of the recorded video. Just record and edit it at the end. PS: 1. This method can only be recorded on the computer version, not on the mobile phone.

See all articles