<repo_name>PhoenixFate/darkhorse297-jpa<file_sep>/spring-data-jpa/src/test/java/com/phoenix/test/CustomerObjectNavigationTest.java
package com.phoenix.test;

import com.phoenix.dao.CustomerDao;
import com.phoenix.dao.LinkManDao;
import com.phoenix.domain.Customer;
import com.phoenix.domain.LinkMan;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * important
 * 对象导航查询
 */
@RunWith(SpringJUnit4ClassRunner.class) //声明spring提供的单元测试环境
@ContextConfiguration(locations = "classpath:applicationContext.xml")  //指定spring容器的配置信息
public class CustomerObjectNavigationTest {

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private LinkManDao linkManDao;

    /**
     * 测试对象导航（查询一个对象的时候，通过此对象查询所有的关联对象）
     */
    @Test
    @Transactional
    @Rollback(value = false)
    public void testObjectNavigation(){
        //getOne() 延迟加载
        Customer customer = customerDao.getOne(5L);
        //对象导航查询
        Set<LinkMan> linkMans = customer.getLinkMans();
        for(LinkMan linkMan:linkMans){
            System.out.println(linkMan);
        }

    }

    /**
     * 测试对象导航（查询一个对象的时候，通过此对象查询所有的关联对象）
     *
     * 对象导航查询
     *      默认使用的是延迟加载的形式查询的
     *          调用get方法并不会立即发送查询，而是在使用关联查询对象的时候才会延迟查询
     * 可修改配置，将延迟加载改为立即加载
     *      fetch，需要配置到多表映射的关系的注解上
     */
    @Test
    @Transactional
    @Rollback(value = false)
    public void testObjectNavigation2(){
        //findOne() 立即加载
        Customer customer = customerDao.findOne(5L);
        //对象导航查询
        Set<LinkMan> linkMans = customer.getLinkMans();
        for(LinkMan linkMan:linkMans){
            System.out.println(linkMan);
        }

    }


    /**
     * 从多的一方查询一的一方，默认是立即加载
     * 从联系人对象导航查询他所属的客户
     */
    @Test
    @Transactional
    @Rollback(value = false)
    public void testObjectNavigation3(){
        LinkMan linkMan = linkManDao.findOne(1L);
        Customer customer = linkMan.getCustomer();
        System.out.println(customer);
    }


}
<file_sep>/spring-data-jpa/src/test/java/com/phoenix/test/CustomerSqlTest.java
package com.phoenix.test;

import com.phoenix.dao.CustomerDao;
import com.phoenix.domain.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class) //声明spring提供的单元测试环境
@ContextConfiguration(locations = "classpath:applicationContext.xml")  //指定spring容器的配置信息
public class CustomerSqlTest {

    @Autowired
    private CustomerDao customerDao;

    @Test
    public void testFindAllBySql(){
        List<Customer> customerList = customerDao.findAllBySql();
        for(Customer customer:customerList){
            System.out.println(customer);
        }
    }

    @Test
    public void testFindByNameBySql(){
        List<Customer> customerList=customerDao.findByNameBySql("%tomcat%");
        for(Customer customer:customerList){
            System.out.println(customer);
        }
    }


}
<file_sep>/spring-data-jpa/src/test/java/com/phoenix/test/CustomerTest.java
package com.phoenix.test;

import com.phoenix.dao.CustomerDao;
import com.phoenix.domain.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class) //声明spring提供的单元测试环境
@ContextConfiguration(locations = "classpath:applicationContext.xml")  //指定spring容器的配置信息
public class CustomerTest {

    @Autowired
    private CustomerDao customerDao;

    @Test
    public void testFindAll(){
        List<Customer> customerList = customerDao.findAll();
        for(Customer customer:customerList){
            System.out.println(customer);
        }
    }

    @Test
    public void testFindOne(){
        Customer one = customerDao.findOne(2l);
        System.out.println(one);
    }


    /**
     * save 保存或者更新
     *      根据传递的对象释放存在主键id
     *      如果没有id主键属性：保存
     *      存在id主键属性，则根据id查询数据，更新数据
     */
    @Test
    public void testSave(){
        Customer customer=new Customer();
        customer.setCustName("spring data jps");
        customer.setCustAddress("spring address");
        customer.setCustIndustry("spring industry");
        customerDao.save(customer);
    }

    @Test
    public void testUpdate(){
        Customer customer = customerDao.findOne(7L);
        customer.setCustLevel("new level");
        customerDao.save(customer);
    }


    @Test
    public void testDelete(){
        customerDao.delete(7L);

    }


    /**
     * 统计查询，查询总数
     */
    @Test
    public void testCount(){
        long count = customerDao.count();
        System.out.println(count);
    }


    /**
     * 判断id为4的客户是否存在
     */
    @Test
    public void testExists(){
        boolean exists = customerDao.exists(4L);
        System.out.println("id 为4的客户是否存在："+exists);

    }


    /**
     * getOne()
     *    需要在方法名上面+ @transactional 保证正常运行
     *
     * findOne():
     *      entityManager.find()  立即加载
     *
     * getOne():
     *      entityManager.getReference()  延迟加载
     *
     */
    @Test
    @Transactional
    public void testGetOne(){
        Customer customer = customerDao.getOne(4L);
        System.out.println(customer);

    }



}
<file_sep>/common-jpa/src/test/java/com/phoenix/test/JpaTest.java
package com.phoenix.test;

import com.phoenix.pojo.Customer;
import com.phoenix.util.JpaUtil;
import org.junit.Test;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;


public class JpaTest {
    /**
     * 测试jpa的保存
     * jpa的操作步骤
     *    1.加载配置文件创建工厂（实体管理器工厂）对象
     *    2.通过实体管理器工厂获取实体管理器
     *    3.获取事物对象，开启事务
     *    4.完成增删改查操作
     *    5.提交事务（回滚事务）
     *    6.释放资源
     */
    @Test
    public void testSave(){
        //1.加载配置文件创建工厂（实体管理器工厂）对象
        //persistenceUnitName 就是persistence.xml中配置的name
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myJpa");
        //2.通过实体管理器工厂获取实体管理器
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        //3.获取事物对象，开启事务
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();

        Customer customer=new Customer();
        customer.setCustName("tomcat");
        customer.setCustIndustry("it");
        //4.完成增删改查操作
        entityManager.persist(customer);//保存操作
        //5.提交事务（回滚事务）
        transaction.commit();
        //6.释放资源
        entityManager.close();
        entityManagerFactory.close();
    }

    @Test
    public void testSaveByUtil(){
        //1.通过工具类获取entityManager对象
        EntityManager entityManager = JpaUtil.getEntityManager();
        //2.获取事物对象，开启事务
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();

        Customer customer=new Customer();
        customer.setCustName("tomcat2");
        customer.setCustIndustry("it2");
        //3.完成增删改查操作
        entityManager.persist(customer);//保存操作
        //4.提交事务（回滚事务）
        transaction.commit();
        //5.释放资源
        entityManager.close();
    }


    /**
     * find：（立即加载）
     *    立即发送sql进行查询
     */
    @Test
    public void testFindById(){
        //1.通过工具类获取entityManager对象
        EntityManager entityManager = JpaUtil.getEntityManager();
        //2.获取事物对象，开启事务
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        /**
         * find 根据id查询数据
         *      class查询数据的结果需要包装的实体类类型的字节码
         *      id 查询的主键
         */
        Customer customer = entityManager.find(Customer.class, 2L);
        System.out.println(customer);

        //4.提交事务（回滚事务）
        transaction.commit();
        //5.释放资源
        entityManager.close();

    }

    /**
     * getReference: （延时加载）
     *      1.获得的对象是一个动态代理对象
     *      2.调用getReference不会立即发送sql语句查询数据库
     *          当调用结果对象的时候，才会发送sql进行查询
     */
    @Test
    public void testReferenceById(){
        //1.通过工具类获取entityManager对象
        EntityManager entityManager = JpaUtil.getEntityManager();
        //2.获取事物对象，开启事务
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        /**
         * find 根据id查询数据
         *      class查询数据的结果需要包装的实体类类型的字节码
         *      id 查询的主键
         */
        Customer customer = entityManager.getReference(Customer.class, 2L);
        System.out.println(customer);

        //4.提交事务（回滚事务）
        transaction.commit();
        //5.释放资源
        entityManager.close();

    }

    /**
     * jpa更新数据
     */
    @Test
    public void testUpdate(){
        //1.通过工具类获取entityManager对象
        EntityManager entityManager = JpaUtil.getEntityManager();
        //2.获取事物对象，开启事务
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();

        Customer customer = entityManager.find(Customer.class, 2L);
        customer.setCustName("merge2");
        Customer merge = entityManager.merge(customer);
        System.out.println(merge);

        //4.提交事务（回滚事务）
        transaction.commit();
        //5.释放资源
        entityManager.close();
    }

    /**
     * jpa删除数据
     */
    @Test
    public void testRemove(){
        //1.通过工具类获取entityManager对象
        EntityManager entityManager = JpaUtil.getEntityManager();
        //2.获取事物对象，开启事务
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();

        Customer customer = entityManager.find(Customer.class, 1L);
        entityManager.remove(customer);


        //4.提交事务（回滚事务）
        transaction.commit();
        //5.释放资源
        entityManager.close();
    }

}
<file_sep>/README.md
## jpa

## jpa规范
![jpa规范](./images/01-jpa规范.png)



## springData jpa规范
### springDataJpa jpa hibernate关系
![三者关系](images/02-springDataJpa-jpa-hibernate关系.png)






<file_sep>/spring-data-jpa/src/test/java/com/phoenix/test/CustomerJpqlTest.java
package com.phoenix.test;

import com.phoenix.dao.CustomerDao;
import com.phoenix.domain.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class) //声明spring提供的单元测试环境
@ContextConfiguration(locations = "classpath:applicationContext.xml")  //指定spring容器的配置信息
public class CustomerJpqlTest {

    @Autowired
    private CustomerDao customerDao;

    @Test
    public void testFindByNameJpql(){
        Customer customer = customerDao.findByNameByJpql("tomcat4");
        System.out.println(customer);
    }

    @Test
    public void testFindByNameAndIdJpql(){
        Customer customer = customerDao.findByNameAndIdByJpql("tomcat4",4L);
        System.out.println(customer);
    }

    /**
     * springdata-jpa中使用update更新操作，
     * 1.需要手动添加事务 @transactional
     * 2.并且默认会自动回滚，需要手动添加 @rollback(value=false)
     *
     */
    @Test
    @Transactional  //添加事务支持
    @Rollback(value = false)
    public void testUpdate(){
        customerDao.updateCustomerName("update by jpql",4L);
    }

}
