JPA入门之HelloWorld

利用空余的时间学习了JPA,刚写完一个HelloWorld就来写这篇博客,记录一下自己的编程之路。接下来就步入正题:让我们来搭建一个JPA的环境,小编依旧使用的是IDEA,在这里要特别说明:使用IDEA搭建JPA时,IDE自动生成的persistence.xml不是在resources源码包下,这是运行就会抛出异常,说找不到persistence.xml,因此我们需要把persistence.xml拷贝到resources下。
一 :工程目录结构
![工程目录结构图](https://img-blog.csdn.net/20170406102855026?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveWdlbmdsZW1hbg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
二 :创建实体类
/**
 * @Table 表明该持久化类生成的数据表的表名称
 * @Entity 标识该类是一个持久化类
 */
@Table(name = "jpa_customer")
@Entity
public class Customer {

    private Integer id;

    private Integer age;

    private String lastName;

    private String email;

    private Date createDate; //创建时间

    private Date birth; //生日

    public Customer() {
    }

    public Customer(Integer age, String lastName, String email) {
        this.age = age;
        this.lastName = lastName;
        this.email = email;
    }

    public Customer(Integer id, Integer age, String lastName, String email) {
        this.id = id;
        this.age = age;
        this.lastName = lastName;
        this.email = email;
    }

    /**
     * @GeneratedValue 标明主键的生成策略
     *  1:GenerationType.AUTO 默认的生成策略,JPA会根据数据库选择合适的策略
     *  2:GenerationType.SEQUENCE 序列
     *  3: GenerationType.IDENTITY 采用数据库自增 oracle不支持此策略
     *  @Id :标明主键
     * @return
     */
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * 对于 Date 类型的属性,若我们不做任何标识
     * 那么在生成的数据表所对应的字段类型为 dateTime,
     * 然而对于一些特殊的字段就不能满足我们的需求,因此我们可以使用
     *
     * @return
     */
    @Temporal(TemporalType.TIMESTAMP)  //时间戳,对应数据表的类型为dateTime
    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    @Temporal(TemporalType.DATE)  //精确到年月日, 对应数据表的类型为date
    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    /**
     * 若在get方法上没有任何注解,那么Jpa会在该get方法上
     * 默认添加 @Basic 注解
     * @return
     */
    @Basic
    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    /**
     * @Column : 可以定义该字段生成数据表的字段名称,长度....
     * @return
     */
    @Column(name = "last_name", length = 50, nullable = false, unique = true)
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", age=" + age +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                '}';
    }

    /**
     * 对于这种自定义的方法,我们并不需要将他映射为数据表的字段
     * IDEA非常智能,当发现该方法没有对应的setInfo()方法时,IDEA
     * 会提示错误,运行时就会抛出异常:
     * org.hibernate.PropertyNotFoundException:
     * Could not find a setter for property info in class org.jpa.entity.Customer
     * 因此我们可以使用 @Transient 注解标识它
     * @return
     */
    @Transient
    public String getInfo(){
        return "getInfo";
    }
}

二 :编写persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<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
             http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="jpa01" transaction-type="RESOURCE_LOCAL">

        <!-- 配置使用什么ORM来实现JPA , 注意由于本人使用的是Hibernate4.1.9.Final,
            hibernate-entitymanager 4.1.9.Final,在高版本中此方法已被弃用了
        -->
        <provider>org.hibernate.ejb.HibernatePersistence</provider>

        <!-- 添加持久化类 -->
        <class>org.jpa.entity.Customer</class>
        <properties>

            <!-- 连接数据库的基本信息 -->
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql:///jpa"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value="root"/>

            <!-- 配置JPA实现产品的基本信息,实际上是配置Hibernate的基本信息 -->
            <!-- 显示SQL语句 -->
            <property name="hibernate.show_sql" value="true"/>
            <!-- 格式化SQL语句 -->
            <property name="hibernate.format_sql" value="true"/>
            <!-- 生成表策略 -->
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>

</persistence>

三 :测试类

public class Main {

    public static void main(String[] args) {

        //创建EntityManagerFactory
        String name = "jpa01" ;
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(name);

        //创建EntityManager
        EntityManager entityManager = entityManagerFactory.createEntityManager();

        //开启事务
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();

        //持久化数据
        Customer customer = new Customer(21, "Jerry", "Jerry@163.com");
        customer.setCreateDate(new Date());
        customer.setBirth(new Date());
        entityManager.persist(customer);

        //提交事务
        transaction.commit();

        //关闭EntityManagerFactory
        entityManagerFactory.close();

        //关闭EntityManager
        entityManager.close();
    }
}

四:pom.xml

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.hibernate.common</groupId>
      <artifactId>hibernate-commons-annotations</artifactId>
      <version>4.0.2.Final</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.1.9.Final</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate.javax.persistence</groupId>
      <artifactId>hibernate-jpa-2.0-api</artifactId>
      <version>1.0.1.Final</version>
    </dependency>
    <dependency>
      <groupId>org.jboss.logging</groupId>
      <artifactId>jboss-logging</artifactId>
      <version>3.1.0.GA</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.6.0</version>
    </dependency>
    <dependency>
      <groupId>org.jboss.spec.javax.transaction</groupId>
      <artifactId>jboss-transaction-api_1.1_spec</artifactId>
      <version>1.0.1.Final</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>4.1.9.Final</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.persistence</groupId>
      <artifactId>javax.persistence</artifactId>
      <version>2.1.0-RC2</version>
    </dependency>
    <dependency>
      <groupId>dom4j</groupId>
      <artifactId>dom4j</artifactId>
      <version>1.6.1</version>
    </dependency>
    <dependency>
      <groupId>antlr</groupId>
      <artifactId>antlr</artifactId>
      <version>2.7.7</version>
    </dependency>
    <dependency>
      <groupId>org.javassist</groupId>
      <artifactId>javassist</artifactId>
      <version>3.15.0-GA</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.18</version>
    </dependency>
    <!-- hibernate 二级缓存 -->
    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache-core</artifactId>
      <version>2.4.3</version>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-ehcache</artifactId>
      <version>4.2.4.Final</version>
    </dependency>

    <dependency>
      <groupId>org.jboss.logging</groupId>
      <artifactId>jboss-logging</artifactId>
      <version>3.1.0.CR2</version>
    </dependency>

    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.1</version>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>4.2.0.Final</version>
    </dependency>

    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version></version>
    </dependency>

  </dependencies>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值