依赖导入
<!-- hibernate 核心 -->
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.2.7.Final</version>
</dependency>
<!-- jdbc 实现 -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!-- 会话工厂 -->
<session-factory>
<!-- 链接参数 -->
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/jpa_study?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">a1b2c3</property>
<!-- 显示sql语句 -->
<property name="show_sql">false</property>
<!-- 格式化sql -->
<property name="format_sql">false</property>
<!-- sql方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 自动操作:创建-删除 -->
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<!-- 配置sessionFactory.getCurrentSession()的上下文 -->
<property name="current_session_context_class">thread</property>
<!-- 导入实体类和映射关系 -->
<mapping class="org.example.entity.User"/>
<mapping class="org.example.entity.Address"/>
<mapping class="org.example.entity.Vlog"/>
<mapping class="org.example.entity.Role"/>
</session-factory>
</hibernate-configuration>
一对一
User 实体类
@Entity
@Table(name = "user")
@Data
public class User {
/*...省略其他内容*/
// 关联列的名称:address_id
@JoinColumn(name = "address_id")
@OneToOne(
// 懒加载
fetch = FetchType.LAZY
)
private Address address;
}
Address 实体类
@Entity
@Setter
@Getter
@Table(name = "address")
public class Address {
/*...省略其他内容*/
@OneToOne(
// 实体关联的被拥有者,只想User.address字段
mappedBy = "address"
)
private User user;
}
测试
@Test
public void oneToOneTest() {
AddressDao addressDao = new AddressDao();// Dao层已经在https://www.cnblogs.com/heirem/p/17616689.html说过了,这里就放代码了
Address address = new Address();
address.setDetail("广东中山");
addressDao.save(address);
UserDao userDao = new UserDao();
User user = new User();
user.setName("张三");
user.setEmail("zhangsan@email.com");
userDao.save(user);
user.setAddress(address);
userDao.update(user);
userDao.findAll().forEach(System.out::println);
}
User(id=1, name