JPA primary key generation strategy dirty data entity object status update the relationship between the two cache entries

What is the primary key:
1. Can not be null and the only,
2. uniquely identify (distinguish it from other keys in each row)

Primary Category:
surrogate primary key:

  • Use column moot as a primary key (such as id)

Natural primary key:

  • Use specific practical significance of the primary key (like the name) as a column

Primary key generation strategy


若是交给了jpa主键策略@GeneratedValue 在保存数据的时候就不需要设置该主键的值了因为这个值已经交给jap进行维护了


  @GeneratedValue(strategy=GenerationType.AUTO)         
 自己会根据你的配置的方言 来选择使用的生成策略 -- 主键自增(mysql) --序列(oracle)


@GeneratedValue (strategy = GenerationType.IDENTITY)
                                          主键由数据库自动生成(主要是自动增长型)  

            
@GeneratedValue (strategy = GenerationType.SEQUENCE)
                                        序列 mysql不支持 但是oracle支持序列        
      
@GeneratedValue(strategy = GenerationType.TABLE) 
                                       表的策略 兼容好 可以mysql 支持oracle 性能有点低() 使用一个特定的数据库表格来保存主键。

JPA entity object state:

Instantaneous state :
just created out of the (new) and entityManager not a relationship (part of temporary objects)
hosted Status:
already entityManger relationship (additions and deletions to call the method when) a relationship persisted added to the cache has occurred entityManager (for a cache fill)
in the free state :
already departing entity relationship has persisted, but not at the entityManager. (Analogous to breaking up)
Delete state
if we want to delete a content remove this status only called entityManager.remove (domain objects) method of the object associated ID, and in entityManager management, but has been scheduled to be deleted, the transaction will be submitted really It has been deleted.

Dirty data update:

What is dirty:

  1. Refers to the system data source is not given range for the actual traffic or meaningless, or illegal data format, and the presence of non-standard ambiguous code and business logic in the source system.
  2. Popular talk is when a transaction is accessing data, and the data has been modified, and this modification has not been submitted to the database, then, another transaction also access the data, and then use this data. This data because the data is not yet committed, then another transaction read this data is dirty data, the operation may be made to the dirty data is incorrect.

Dirty data update:

If you modify the value of the primary key n-to-n issue will error
data a persistent state, if you modify the value of the non-primary key in commit time, will automatically send the update statement updates

Code reflects

  @Test
         public void test01(){

         /*
          *    当我查询一条数据的时候 从数据库里面拿到值
          *    此时实例entil对象状态改变改为托管状态持久化状态
          *     当你拿到查询到的值(此时的值是缓存中的值)然后修改它 此时修改后的值存在在内存里面
          *    当你提交事务的时候
          *    jpa会将内存中的值跟缓存中的进行比较若是一致则不修改值 若是不一致则修改缓存里面的值修改数据库里面的值
          */
         EntityManager manager = Util.getEntityManager();
         manager.getTransaction().begin();
         // 此时这个对象已经被持久化并且添加到一级缓存里面了
         Student student = manager.find(Student.class, 1L);
         //设置值
         student.setName("你几号啊");
         Student student1 = manager.find(Student.class, 1L);
         System.out.println(student.equals(student1));
         manager.getTransaction().commit();
         System.out.println(student);
         manager.close();
     }

Entity definition rules:

  1. Entity class can not be defined as final (final) types because they can not be inherited later tell * lazyload when using lazy loading, creates a subclass of code in memory
    2. If you can not find the use of a field using lazy loading entities inside all many types of packaging underlying code is determined not null
    3. If the comparison how the basic data types is null if the entity has a structure inside method parameters, must be configured to provide a non-parametric methods
    such as the use find, configuration parameters to be used without method to create an object

Relationships between entities:

Dependencies:
dependency injection (the DI): the subject is injected into the class, a process called dependency injection (IOC inversion of control)

Relationship (jpa difficulty): according to the content or nature of points: there is correlation between employees and departments, such as classes and

  • Corresponds to a multiple many-member department
  • Many: a corresponding number of student teacher
  • To-many: a character (actor student teacher) correspond more rights, a rights managed multiple roles
  • One: one corresponding to a monogamous ID number corresponding to a spatial qq qq a
    navigational resistance rating:
    unidirectional : only get another side b side from the A side, but the party is unable to obtain a b side (single Love crush)
    two-way : ** love each other can get
    a one-way many-to-staff and departments

Combination relationship:
(many-to-many between part and whole, whole and part can not be separated), such as the site and the people
reflected in the project: for example, involves documents when you place the order the next one after that is not in the background part of divisible

Aggregation relationship:
(many-to-many and integrally between the portions, and the integral portions may exist separately)
desktop computer mouse hard fan
generalization relationship: Inheritance reflected

Many-relationship combination of individual code to achieve:

 @Test
    public void testname() throws Exception {
    /*若是先保存多方在保存一方则 发送sql为3条  反之为5条
当你将一方的方在上面先执行的时候 先设置的值为dir  然后在设置 员工对象里面的name和age 若是你先保存多方的值则
 先设置 员工表的 age和nane 然后再去设置部门表的 name 此时员工表的外键 idr是没有值的 当你设 他会在发送两条修改的sql 修改值
Hibernate: update t_employee set age=?, dpt_id=?, name=? where id=?
 Hibernate: update t_employee set age=?, dpt_id=?, name=? where id=?
  */
        // 单项多对一
        Department department = new Department();
        department.setName("市场部");// 设置部门
        employee employee = new employee();//创建第一个员工对象
        employee.setAge(22);//设置值
        employee.setName("小胡");
         employee.setDpt(department);// 设置外键
        employee employee2 = new employee();//第二个员工对象
        employee2.setAge(22);
        employee2.setName("小xiang");
        employee2.setDpt(department);
        EntityManager manager = Util.getEntityManager();
        manager.getTransaction().begin();
        
        manager.persist(department);
        manager.persist(employee);
        manager.persist(employee2);
        manager.getTransaction().commit();
        manager.close();
    }

Lazy load and emergency load:

       懒加载@ManyToOne(fetch = FetchType.LAZY) 
        就是当你需要的时候采取数据库里面取数据:
        延时加载   即需要使用的时候采取加载可能会相对慢点但是对于内存占用率少
       急加载 @ManyToOne(fetch = FetchType.EAGER)
       同懒加载相反

Lazy record underlying principle: Why not use finad
lazy load test code

  @Test
    public void testLazy()throws Exception{
/*
* 理解 底层原理  懒加载
 *          非find--查询出来放入缓存里面employee 把放入缓存里面
 *          第二次在获取的时候,从缓存里面找是否有分类的名称,如果没有分类名称
 *          getName,在发送sql查询分类名称
 *         延迟加载 跟你生成额外的 departenmt的子类 cn.itsource.jpa.Departmentt_$$_jvsta7d_1 若是使用find 则无法生成子类则
 *         无法使用懒加载默认急加载
* */
        EntityManager entityManager = Util.getEntityManager();
        employee employee = entityManager.find(employee.class, 8L);
        //得到分类名称
        if(employee.getDpt() == null){
            System.out.println("没有外键");
        }else{
            System.out.println("有外键");
        }
        System.out.println(employee.getDpt().getName());//.getName 的时候才发出sql语句
        System.out.println(employee.getDpt().getClass());//延迟加载 跟你生成额外的 departenmt的子类 cn.itsource.jpa.Departmentt_$$_jvsta7d_1


    }

Secondary cache:
What is the second-level cache:

Cache hit conditions:

A cache hit conditions:
the same objects in the same plant with the same object management oid
two cache hit conditions:
Different objects of the same plant with the same object management oid

When to use secondary cache:

  1. Reading greater than the modified because when the modified data, cache synchronization change
  2. To have exclusive control of the data, the data will not be third-party modifications; If you modify data, the cache also need to change
  3. Inside the data cache can tolerate invalid data (such as log information for less demanding real-time data)
  4. If a large amount of data, do not fit into the cache (passivation encache support memory disk storage)

Test two cache code

@Test
          public void test11()throws  Exception{
        /*      当我们第一次查询到数据的时候会将数据放入一级缓存和二级缓存里面 一级缓存依赖的是管理着对象
             二级缓存依赖的是工厂对象 两种方式依赖的对象不一样
        *       当我们使用 manger。close的时候是清除一级缓存二级缓存并没有被清除
        *       所以当我们使用不同的管理着对象查询的时候先去的一级缓存里面找然后去二级缓存里面找
        *        若是匹配则 直接拿来用所以 此代码只发送一条sql语句
        * */


            // 测试二级缓存  同一个 共工厂对象  不同的管理着对象  同一个oid
          EntityManager manager1 = Util.getEntityManager();
          manager1.find(employee.class, 8L);
          manager1.close();
          EntityManager manager2 = Util.getEntityManager();
          manager2.find(employee.class,8L );
          manager2.close();
      }

Secondary cache Notes codes:

@Test
        public void test12()throws  Exception{
     /*        当我们在find查询方法之前床创建对象的时候 此的的这个对象是顺时状态 所以没有加入二级缓存
     *           若是在find之后创建的对象就会加如二级缓存
                   此代码发送两条sql
            
     * */

        EntityManager manager1 = Util.getEntityManager();
        EntityManager manager2 = Util.getEntityManager();
        manager1.find(employee.class,8L );
        manager1.close();
        manager2.find(employee.class,8L );
        manager2.close();

        }


}
Published 23 original articles · won praise 2 · Views 943

Guess you like

Origin blog.csdn.net/metjoyful/article/details/101063919