JPA的基本使用

11 篇文章 0 订阅
1 篇文章 0 订阅

1.创建maven工厂导入依赖

  <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.0.12.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>5.0.12.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
    </dependencies>

2.在resources下创建META-INF文件夹,然后在创建persistence.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <!--
        配置持久化单元
        transaction-type=JTA 分布式
        transaction-type=RESOURCE_LOCAL  本地事务
    -->
    <persistence-unit name="myJPA" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value="123123"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql:///jpa"/>
            <!--控制台打印sql-->
            <property name="hibernate.show_sql" value="true"/>
            <!--实体类自动创建表-->
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>
</persistence>

3.编写实体类完成 表和实体类的映射关系

@Entity
@Table(name = "t_user")
public class User {
    public User() {
    }

    public User(Integer id, String userName, Integer age) {
        this.id = id;
        this.userName = userName;
        this.age = age;
    }

    /**
     * 主键生成策略
     * IDENTITY 适合mysql自增
     * SEQUENCE 适合oracle
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;
    @Column(name = "user_name")
    private String userName;
    private Integer age;

    set..
    get..
}

4.编写测试类进行测试

public class JpaTest {
    private  static EntityManagerFactory entityManagerFactory;
    static {
        entityManagerFactory = Persistence.createEntityManagerFactory("myJPA");
    }
    //提取成一个工具类
    public static EntityManager createEntityManager(){
        return entityManagerFactory.createEntityManager();
    }
    @Test
    public void testSave() throws IOException {

        /**
         *jpa操作七步骤
         * 1.加载配置创建工厂对象
         * 2.工厂创建实体管理对象
         * 3.管理对象开启事务
         * 4.管理对象完成CRUD
         * 5.管理对象回滚事务
         * 6.管理对象完成事务提交
         * 7.管理对象释放事务
         */

        //1.加载配置创建工厂对象
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myJPA");
        //2.工厂创建实体管理对象
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        //3.管理对象开启事务
        transaction.begin();
        try {
            User user = new User(null,"张大宝2",18);
            //4.管理对象完成CRUD
            entityManager.persist(user); //保存操作
            //5.管理对象完成事务提交
            transaction.commit();
        }catch (Exception e){
            //6.管理对象回滚事务
            transaction.rollback();
        }finally {
            //7.管理对象释放事务
            if(entityManager != null){
                entityManager.close();
            }
            if(entityManagerFactory != null){
                entityManagerFactory.close();
            }
        }

    }

    //查询方法
    @Test
    public void find(){
        //2.工厂创建实体管理对象
        EntityManager entityManager = JpaTest.createEntityManager();
        //立即查询sql
        User user = entityManager.find(User.class, 1);
        System.out.println(user);
        //延迟查询sql
        User user2 = entityManager.getReference(User.class, 1);
        System.out.println(user2);
        if(entityManager != null){
            entityManager.close();
        }
    }
    //更新方法
    @Test
    public void update(){
        EntityManager entityManager = JpaTest.createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        User user = entityManager.getReference(User.class, 1);
        user.setUserName("new王大宝");
        transaction.begin();
        User merge = entityManager.merge(user);
        transaction.commit();
        if(entityManager != null){
            entityManager.close();
        }
    }
    //删除方法
    @Test
    public void remove(){
        EntityManager entityManager = JpaTest.createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        User user = entityManager.getReference(User.class, 1);
        entityManager.remove(user);
        transaction.commit();
        if(entityManager != null){
            entityManager.close();
        }
    }
}

提示

表是不用自己创建的,只需要指定好数据库即可

1.JPQL基本使用语法,JPQL和SQL语法区别是JPQL操作的都是对象名和属性,SQL操作表和字段

public class JpqlTest {
    /**
     * jpql查询语法演示
     */
    @Test
    public void find(){
        EntityManager entityManager = JpaTest.createEntityManager();
        //查询全部
        System.out.println("====================查询全部====================");
        String jpql="from com.yujie.model.User";
        Query query = entityManager.createQuery(jpql);
        List resultList = query.getResultList();
        for (Object o : resultList) {
            System.out.println(o);
        }

        //统计个数
        System.out.println("====================统计个数====================");
        jpql="select count(id) from com.yujie.model.User";
        query = entityManager.createQuery(jpql);
        Object singleResult = query.getSingleResult();
        System.out.println(singleResult);

        //分页查询
        System.out.println("====================分页查询====================");
        jpql="From com.yujie.model.User";
        query = entityManager.createQuery(jpql);
        query.setFirstResult(0);
        query.setMaxResults(5);
        List resultLimit = query.getResultList();
        for (Object o : resultLimit) {
            System.out.println(o);
        }

        //倒序查询
        System.out.println("====================倒序查询====================");
        jpql="from com.yujie.model.User order by id desc";
        query = entityManager.createQuery(jpql);
        List resultDesc= query.getResultList();
        for (Object o : resultDesc) {
            System.out.println(o);
        }

        //条件查询
        System.out.println("====================条件查询====================");
        jpql="from com.yujie.model.User where id=? and userName=?";
        query = entityManager.createQuery(jpql);
        query.setParameter(1,1);
        query.setParameter(2,"张大宝");
        List resultList1 = query.getResultList();
        for (Object o : resultList1) {
            System.out.println(o);
        }

        //模糊查询
        System.out.println("====================模糊查询====================");
        jpql="from com.yujie.model.User where userName like ?";
        query = entityManager.createQuery(jpql);
        query.setParameter(1,"老%");
        List resultLike = query.getResultList();
        for (Object o : resultLike) {
            System.out.println(o);
        }
    }
}

打印结果

====================查询全部====================
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.user_name as user_nam3_0_ from t_user user0_
User{id=1, userName='张大宝', age=18}
User{id=2, userName='老六', age=18}
====================统计个数====================
Hibernate: select count(user0_.id) as col_0_0_ from t_user user0_
2
====================分页查询====================
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.user_name as user_nam3_0_ from t_user user0_ limit ?
User{id=1, userName='张大宝', age=18}
User{id=2, userName='老六', age=18}
====================倒序查询====================
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.user_name as user_nam3_0_ from t_user user0_ order by user0_.id desc
User{id=2, userName='老六', age=18}
User{id=1, userName='张大宝', age=18}
====================条件查询====================
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.user_name as user_nam3_0_ from t_user user0_ where user0_.id=? and user0_.user_name=?
User{id=1, userName='张大宝', age=18}
====================模糊查询====================
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.user_name as user_nam3_0_ from t_user user0_ where user0_.user_name like ?
User{id=2, userName='老六', age=18}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值