zoukankan      html  css  js  c++  java
  • JPA笔记1 ManyToOne

    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="jpa-1" transaction-type="RESOURCE_LOCAL">
    
            <provider>org.hibernate.ejb.HibernatePersistence</provider>
    
            <!-- <class>helloworld.Customer</class> -->
            <properties>
    
    
                <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
                <property name="javax.persistence.jdbc.url"
                    value="jdbc:mysql://x.x.x.x:3306/jpa-test?useUnicode=true&amp;characterEncoding=utf8" />
                <property name="javax.persistence.jdbc.user" value="admin" />
                <property name="javax.persistence.jdbc.password" value="123456" />
    
                <property name="hibernate.format_sql" value="true" />
                <property name="hibernate.show_sql" value="true" />
                <property name="hibernate.hbm2ddl.auto" value="update" />
            </properties>
        </persistence-unit>
    </persistence>

    ManyToOne测试代码

    package helloworld;
    
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.EntityTransaction;
    import javax.persistence.Persistence;
    
    public class Main {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    
            String persistenceUnitName = "jpa-1";
            EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName);
    
            EntityManager entityManager = entityManagerFactory.createEntityManager();
    
            EntityTransaction transaction = entityManager.getTransaction();
            transaction.begin();
    
            // insert(entityManager);
            // find(entityManager);
            // getReference(entityManager);
            // remove(entityManager);
            // merge(entityManager);
            // flush(entityManager);
            // manyToOnePersist(entityManager);
            // manyToOneFind(entityManager);
            // manyToOneRemove(entityManager);
            manyToOneUpdate(entityManager);
    
            transaction.commit();
            entityManager.close();
            entityManagerFactory.close();
        }
    
        // 1.插入
        private static void insert(EntityManager entityManager) {
            Customer customer = new Customer();
            customer.setEmail("fs2@ss.com");
            customer.setLastName("123");
            customer.setAge(23);
            customer.setCla(33);
            customer.setFf("aa");
            customer.setId(10);
            entityManager.persist(customer);
        }
    
        // 2.查询(注意,如果修改了对象属性,会被提交到数据库)
        private static void find(EntityManager entityManager) {
            Customer customer = entityManager.find(Customer.class, 1);
            System.out.println("----------------");
            System.out.println(customer);
        }
    
        // 3.引用查询,在调用对象的时候才执行sql
        private static void getReference(EntityManager entityManager) {
            Customer customer = entityManager.getReference(Customer.class, 1);
            System.out.println("----------------");
            System.out.println(customer);
        }
    
        // 4.删除
        private static void remove(EntityManager entityManager) {
            Customer customer = entityManager.find(Customer.class, 2);
            entityManager.remove(customer);
            System.out.println("----------------");
        }
    
        // 5.合并(根据ID判断,存在ID的记录并且数据有变化的则update,不存在则insert)
        private static void merge(EntityManager entityManager) {
            Customer customer = new Customer();
            customer.setEmail("5@ss.com");
            customer.setLastName("4");
            customer.setAge(2);
            customer.setCla(2);
            customer.setFf("3");
    
            Customer customer2 = entityManager.merge(customer);// 没有id,插入数据
    
            System.out.println("----------------" + customer.getId());
            System.out.println("----------------" + customer2.getId());
            System.out.println(customer.equals(customer2));
    
            Customer customer_1 = new Customer();
            customer_1.setEmail("5@ss.com");
            customer_1.setLastName("4");
            customer_1.setAge(21);
            customer_1.setCla(2);
            customer_1.setFf("3");
            customer_1.setId(5);
    
            Customer customer_2 = entityManager.merge(customer_1);// 有id的数据,如果数据有变化则修改
    
            System.out.println("----------------" + customer_1.getId());
            System.out.println("----------------" + customer_2.getId());
            System.out.println(customer_1.equals(customer_2));
        }
    
        // 6.将缓存数据刷新到数据库,不执行该方法,需要在执行commit的时候才提交到数据库
        private static void flush(EntityManager entityManager) {
            Customer customer = entityManager.find(Customer.class, 1);
            System.out.println("----------------");
            customer.setAge(1234);
            entityManager.flush();
            System.out.println(customer);
        }
    
        // 7.保存多对一的数据时,建议先保存一的,再保存多的,这样不会多出update语句
        private static void manyToOnePersist(EntityManager entityManager) {
    
            Order order = new Order();
            order.setOrderName("order1");
    
            Order order2 = new Order();
            order2.setOrderName("order2");
    
            Customer customer = new Customer();
            customer.setEmail("5@ss.com");
            customer.setLastName("4");
            customer.setAge(2);
            customer.setCla(2);
            customer.setFf("3");
    
            order.setCustomer(customer);
            order2.setCustomer(customer);
    
            entityManager.persist(customer);
            entityManager.persist(order);
            entityManager.persist(order2);
    
        }
    
        // 8.查询多对一数据
        private static void manyToOneFind(EntityManager entityManager) {
            Order order = entityManager.find(Order.class, 1);
            System.out.println(order.getOrderName());
            System.out.println(order.getCustomer());
            order.setOrderName("victor");
        }
    
        // 9.不能直接删除一的一端,因为有外键关联
        private static void manyToOneRemove(EntityManager entityManager) {
            Customer customer = entityManager.find(Customer.class, 12);
            entityManager.remove(customer);
        }
    
        // 10.修改多对一数据
        private static void manyToOneUpdate(EntityManager entityManager) {
            Order order = entityManager.find(Order.class, 3);
            order.setOrderName("vv");
            
            order.getCustomer().setAge(100);
        }
    }

    Customer类:

    package helloworld;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Table(name = "JPA_CUSTOMERS")
    @Entity
    public class Customer {
    
        @Override
        public String toString() {
            return "Customer [id=" + id + ", lastName=" + lastName + ", email=" + email + ", age=" + age + ", cla=" + cla + ", ff=" + ff + "]";
        }
    
        private Integer id;
        private String lastName;
        private String email;
        private int age;
        private int cla;
        private String ff;
    
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Id
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        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;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public int getCla() {
            return cla;
        }
    
        public void setCla(int cla) {
            this.cla = cla;
        }
    
        public String getFf() {
            return ff;
        }
    
        public void setFf(String ff) {
            this.ff = ff;
        }
    
    }

    Order类:

    package helloworld;
    
    import javax.persistence.Column;
    import javax.persistence.ConstraintMode;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.ForeignKey;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.ManyToOne;
    import javax.persistence.Table;
    
    @Table(name = "JPA_ORDER")
    @Entity
    public class Order {
    
        private Integer id;
        private String orderName;
    
        private Customer customer;
    
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Id
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        @Column(name = "order_name")
        public String getOrderName() {
            return orderName;
        }
    
        public void setOrderName(String orderName) {
            this.orderName = orderName;
        }
    
        //映射单向n-1的关联关系
        @JoinColumn(name = "customer_id")//, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
        @ManyToOne(fetch=FetchType.LAZY)
        public Customer getCustomer() {
            return customer;
        }
    
        public void setCustomer(Customer customer) {
            this.customer = customer;
        }
    
        @Override
        public String toString() {
            return "Order [id=" + id + ", orderName=" + orderName + ", customer=" + customer + "]";
        }
    
    }
  • 相关阅读:
    shell循环
    shell选择语句
    shell运算符
    shell变量
    前端基础复习
    flask 模板
    flask 会话技术
    flask 项目结构
    Tornado 框架介绍
    flask-models 操作
  • 原文地址:https://www.cnblogs.com/zhuawang/p/11558078.html
Copyright © 2011-2022 走看看