zoukankan      html  css  js  c++  java
  • 双向-外键关联

    一.首先建立工程

    二.导入hibernate核心包和MySQL-connection包,代码如下:

     1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
     3   <modelVersion>4.0.0</modelVersion>
     4   <groupId>com.yztc</groupId>
     5   <artifactId>annotation3</artifactId>
     6   <packaging>war</packaging>
     7   <version>1.0-SNAPSHOT</version>
     8   <name>annotation3 Maven Webapp</name>
     9   <url>http://maven.apache.org</url>
    10   <dependencies>
    11     <dependency>
    12       <groupId>junit</groupId>
    13       <artifactId>junit</artifactId>
    14       <version>4.12</version>
    15       <scope>test</scope>
    16     </dependency>
    17     <dependency>
    18       <groupId>org.hibernate</groupId>
    19       <artifactId>hibernate-core</artifactId>
    20       <version>5.2.11.Final</version>
    21     </dependency>
    22     <dependency>
    23       <groupId>mysql</groupId>
    24       <artifactId>mysql-connector-java</artifactId>
    25       <version>5.1.42</version>
    26     </dependency>
    27   </dependencies>
    28   <build>
    29     <finalName>annotation3</finalName>
    30   </build>
    31 </project>

    三.配置hibernate.cfg.xml文档,代码如下:

     1 <?xml version='1.0' encoding='UTF-8'?>
     2 <!DOCTYPE hibernate-configuration PUBLIC
     3         "-//Hibernate/Hibernate Configuration DTD//EN"
     4         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
     5 <hibernate-configuration>
     6     <session-factory>
     7         <!--数据库连接url配置-->
     8         <property name="connection.url">jdbc:mysql:///hibernate2?useUnicode=true&amp;characterEncoding=UTF-8</property>
     9         <!--数据库驱动配置-->
    10         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    11         <!--数据库用户名配置-->
    12         <property name="connection.username">root</property>
    13         <!--数据库密码配置-->
    14         <property name="connection.password">ROOT</property>
    15         <!-- 方言属性:这个是实现跨数据库关键类 具体查询api-->
    16         <property name="dialect">org.hibernate.dialect.MySQL55Dialect</property>
    17         <!-- 是否显示sql -->
    18         <property name="show_sql">true</property>
    19         <!--是否格式化SQL语句-->
    20         <property name="format_sql">true</property>
    21         <!--是否自动生成表:可选用create update  create-drop validate-->
    22         <property name="hbm2ddl.auto">create</property>
    23         <mapping class="com.yztc.app.entity.Address"/>
    24         <mapping class="com.yztc.app.entity.User"/>
    25     </session-factory>
    26 </hibernate-configuration>

    四.创建entity实体类:User.class和Address.class类,并使用注解,详细代码如下:

     1 package com.yztc.app.entity;
     2 
     3 import org.hibernate.annotations.GenericGenerator;
     4 
     5 import javax.persistence.*;
     6 import java.math.BigDecimal;
     7 
     8 /**
     9  * 一对一
    10  *  单向  主键关联    单向外键关联
    11  *  双向  外键关联
    12  *
    13  */
    14 
    15 @Entity
    16 @Table(name = "TB_USERR")
    17 public class User {
    18     @Id
    19     @Column(name = "USER_ID",length = 32)
    20     @GeneratedValue(generator = "uuuid_generator")//generator 主键生成器
    21     @GenericGenerator(name ="uuuid_generator",strategy = "uuid")//strategy 注解生成器
    22     private String userId;
    23     @Column(name = "NAME",length = 64)
    24     private String name;
    25     @Column(name = "PRICE",precision = 8,scale = 2)
    26     private BigDecimal price;
    27     @Transient
    28     private int state;
    29     @OneToOne(cascade = CascadeType.ALL)
    30     @PrimaryKeyJoinColumn
    31     private Address address;
    32 
    33     public int getState() {
    34         return state;
    35     }
    36 
    37     public void setState(int state) {
    38         this.state = state;
    39     }
    40 
    41 
    42     public BigDecimal getPrice() {
    43         return price;
    44     }
    45 
    46     public void setPrice(BigDecimal price) {
    47         this.price = price;
    48     }
    49 
    50     public Address getAddress() {
    51         return address;
    52     }
    53 
    54     public void setAddress(Address address) {
    55         this.address = address;
    56     }
    57 
    58     public String getUserId() {
    59         return userId;
    60     }
    61 
    62     public void setUserId(String userId) {
    63         this.userId = userId;
    64     }
    65 
    66     public String getName() {
    67         return name;
    68     }
    69 
    70     public void setName(String name) {
    71         this.name = name;
    72     }
    73 
    74     public User() {
    75     }
    76 }
     1 package com.yztc.app.entity;
     2 
     3 import org.hibernate.annotations.GenericGenerator;
     4 import javax.persistence.*;
     5 
     6 @Entity
     7 @Table(name = "TB_ADDRESS")
     8 public class Address {
     9     @Id
    10     @Column(name = "ADD_ID",length = 32)
    11     @GeneratedValue(generator = "uuid")
    12     @GenericGenerator(name = "uuid" ,strategy = "uuid")
    13     private String addId;
    14     @Column()
    15     private String name;
    16     @OneToOne(cascade = CascadeType.ALL)
    17     @JoinColumn(name = "USER_ID")//表示 外键的名称
    18     private User user;
    19 
    20     public User getUser() {
    21         return user;
    22     }
    23 
    24     public void setUser(User user) {
    25         this.user = user;
    26     }
    27 
    28     public String getAddId() {
    29         return addId;
    30     }
    31 
    32     public void setAddId(String addId) {
    33         this.addId = addId;
    34     }
    35 
    36     public String getName() {
    37         return name;
    38     }
    39 
    40     public void setName(String name) {
    41         this.name = name;
    42     }
    43 }

    五.测试类,进行测试,代码如下:

     1 package com.yztc.test;
     2 
     3 import com.yztc.app.entity.Address;
     4 import com.yztc.app.entity.User;
     5 import org.hibernate.Session;
     6 import org.hibernate.SessionFactory;
     7 import org.hibernate.Transaction;
     8 import org.hibernate.cfg.Configuration;
     9 import org.junit.After;
    10 import org.junit.Before;
    11 import org.junit.Test;
    12 
    13 public class TestOneToOne {
    14 
    15     private SessionFactory sf;
    16     private Session session;
    17 
    18     @Before
    19     public void init(){
    20         sf = new Configuration().configure().buildSessionFactory();
    21         session = sf.openSession();
    22 
    23     }
    24     @Test
    25     public void testSave(){
    26         Transaction transaction = session.beginTransaction();
    27 
    28         User user = new User();
    29         user.setName("用户1");
    30         Address address = new Address();
    31         address.setName("深圳");
    32         address.setUser(user);
    33        user.setAddress(address);
    34        session.save(user);
    35         transaction.commit();
    36 
    37 
    38     }
    39     @After
    40     public void destory(){
    41         session.close();
    42     }
    43 }

    六.测试结果:

    "C:Program Files (x86)Javajdk1.8.0_131injava" -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:E:Program FilesJetBrainsIntelliJ IDEA 2017.2.1libidea_rt.jar=56973:E:Program FilesJetBrainsIntelliJ IDEA 2017.2.1in" -Dfile.encoding=UTF-8 -classpath "E:Program FilesJetBrainsIntelliJ IDEA 2017.2.1libidea_rt.jar;E:Program FilesJetBrainsIntelliJ IDEA 2017.2.1pluginsjunitlibjunit-rt.jar;E:Program FilesJetBrainsIntelliJ IDEA 2017.2.1pluginsjunitlibjunit5-rt.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibcharsets.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibdeploy.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibextaccess-bridge-32.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibextcldrdata.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibextdnsns.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibextjaccess.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibextjfxrt.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibextlocaledata.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibext ashorn.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibextsunec.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibextsunjce_provider.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibextsunmscapi.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibextsunpkcs11.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibextzipfs.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibjavaws.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibjce.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibjfr.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibjfxswt.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibjsse.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibmanagement-agent.jar;C:Program Files (x86)Javajdk1.8.0_131jrelibplugin.jar;C:Program Files (x86)Javajdk1.8.0_131jrelib esources.jar;C:Program Files (x86)Javajdk1.8.0_131jrelib t.jar;E:WorkSpacesIdeaProjectAnnotation3 arget est-classes;E:WorkSpacesIdeaProjectAnnotation3 argetclasses;D: oolsmavenapache-maven-3.5.0 epositoryjunitjunit4.12junit-4.12.jar;D: oolsmavenapache-maven-3.5.0 epositoryorghamcresthamcrest-core1.3hamcrest-core-1.3.jar;D: oolsmavenapache-maven-3.5.0 epositoryorghibernatehibernate-core5.2.11.Finalhibernate-core-5.2.11.Final.jar;D: oolsmavenapache-maven-3.5.0 epositoryorgjbossloggingjboss-logging3.3.0.Finaljboss-logging-3.3.0.Final.jar;D: oolsmavenapache-maven-3.5.0 epositoryorghibernatejavaxpersistencehibernate-jpa-2.1-api1.0.0.Finalhibernate-jpa-2.1-api-1.0.0.Final.jar;D: oolsmavenapache-maven-3.5.0 epositoryorgjavassistjavassist3.20.0-GAjavassist-3.20.0-GA.jar;D: oolsmavenapache-maven-3.5.0 epositoryantlrantlr2.7.7antlr-2.7.7.jar;D: oolsmavenapache-maven-3.5.0 epositoryorgjbossspecjavax ransactionjboss-transaction-api_1.2_spec1.0.1.Finaljboss-transaction-api_1.2_spec-1.0.1.Final.jar;D: oolsmavenapache-maven-3.5.0 epositoryorgjbossjandex2.0.3.Finaljandex-2.0.3.Final.jar;D: oolsmavenapache-maven-3.5.0 epositorycomfasterxmlclassmate1.3.0classmate-1.3.0.jar;D: oolsmavenapache-maven-3.5.0 epositorydom4jdom4j1.6.1dom4j-1.6.1.jar;D: oolsmavenapache-maven-3.5.0 epositoryorghibernatecommonhibernate-commons-annotations5.0.1.Finalhibernate-commons-annotations-5.0.1.Final.jar;D: oolsmavenapache-maven-3.5.0 epositorymysqlmysql-connector-java5.1.42mysql-connector-java-5.1.42.jar" com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.yztc.test.TestOneToOne
    十月 13, 2017 7:28:09 下午 org.hibernate.Version logVersion
    INFO: HHH000412: Hibernate Core {5.2.11.Final}
    十月 13, 2017 7:28:09 下午 org.hibernate.cfg.Environment <clinit>
    INFO: HHH000206: hibernate.properties not found
    十月 13, 2017 7:28:10 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
    INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
    十月 13, 2017 7:28:10 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
    WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
    十月 13, 2017 7:28:10 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
    INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql:///hibernate2?useUnicode=true&characterEncoding=UTF-8]
    十月 13, 2017 7:28:10 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
    INFO: HHH10001001: Connection properties: {user=root, password=****}
    十月 13, 2017 7:28:10 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
    INFO: HHH10001003: Autocommit mode: false
    十月 13, 2017 7:28:10 下午 org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
    INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
    十月 13, 2017 7:28:10 下午 org.hibernate.dialect.Dialect <init>
    INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL55Dialect
    十月 13, 2017 7:28:10 下午 org.hibernate.id.UUIDHexGenerator <init>
    WARN: HHH000409: Using org.hibernate.id.UUIDHexGenerator which does not generate IETF RFC 4122 compliant UUID values; consider using org.hibernate.id.UUIDGenerator instead
    十月 13, 2017 7:28:11 下午 org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
    INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@1b2d00b] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
    Hibernate:

    alter table TB_ADDRESS
    drop
    foreign key FK7stsktyes1d808a36kv9wlq0s
    Hibernate:

    drop table if exists TB_ADDRESS
    Hibernate:

    drop table if exists TB_USERR
    Hibernate:

    create table TB_ADDRESS (
    ADD_ID varchar(32) not null,
    name varchar(255),
    USER_ID varchar(32),
    primary key (ADD_ID)
    ) engine=InnoDB
    十月 13, 2017 7:28:11 下午 org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
    INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@15a0c16] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
    Hibernate:

    create table TB_USERR (
    USER_ID varchar(32) not null,
    NAME varchar(64),
    PRICE decimal(8,2),
    primary key (USER_ID)
    ) engine=InnoDB
    Hibernate:

    alter table TB_ADDRESS
    add constraint FK7stsktyes1d808a36kv9wlq0s
    foreign key (USER_ID)
    references TB_USERR (USER_ID)
    十月 13, 2017 7:28:11 下午 org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
    INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@16f8274'
    Hibernate:
    insert
    into
    TB_USERR
    (NAME, PRICE, USER_ID)
    values
    (?, ?, ?)
    Hibernate:
    insert
    into
    TB_ADDRESS
    (name, USER_ID, ADD_ID)
    values
    (?, ?, ?)

    Process finished with exit code 0

    七.表结构:

     

  • 相关阅读:
    ES的基本用法
    Elasticsearch安装部署
    jquery-layer弹框在火狐浏览器中弹框不显示的问题
    MySQL中横表和竖表相互转换
    echarts--迁徙图特性简介
    Lucene入门案例一
    Lucene入门简介
    SpringMVC中的拦截器
    SpringMVC中Json数据格式转换
    SpringMVC中的文件上传
  • 原文地址:https://www.cnblogs.com/1218-mzc/p/7662989.html
Copyright © 2011-2022 走看看