hibernate 自动生成表的方法

第一种方式:

配置 hibernate.cfg.xml

修改文件中的hibernate.hbm2ddl.auto 属性配置:

Xml代码 

 收藏代码

  1. <!--   
  2.     create:先删除,再创建  
  3.     update:如果表不存在就创建,不一样就更新,一样就什么都不做。  
  4.     create-drop:初始化时创建表,SessionFactory执行close()时删除表。  
  5.     validate:验证表结构是否一致,如果不一致,就抛异常。  
  6. -->  
  7. <property name="hibernate.hbm2ddl.auto">update</property>  

 

第二种方式:

在配置文件hibernate.cfg.xml配置映射关系

<mapping resource="com/test/entity/UserData.hbm.xml" />

使用hibernate提供的一个工具类。

org.hibernate.tool.hbm2ddl.SchemaExport

Java代码 

 收藏代码

  1.  
  2. public class TableTest{  
  3.   
  4.     public static void main(String[] args) {  
  5.         // 根据hibernate核心配置文件生成表结构  
  6.         Configuration cfg = new Configuration();  
  7.         cfg.configure("hibernate.cfg.xml");  
  8.         SchemaExport schemaExport = new SchemaExport(cfg);  
  9.           
  10.         boolean script = true;  
  11.         boolean export = true;  
  12.         /** 
  13.          * 创建表结构 
  14.          * 第一个参数script的作用:print the DDL to the console 
  15.          * 第二个参数export的作用:export the script to the database 
  16.          */  
  17.         schemaExport.create(script, export);  
  18.           
  19.         // drop 表结构  
  20.         // schemaExport.drop(script, export);  
  21.     }  
  22.   
  23. }  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中使用JPA和Hibernate生成,需要完成以下步骤: 1. 添加相关依赖:在pom.xml文件中添加Spring Data JPA和Hibernate的依赖。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> </dependency> ``` 2. 配置数据源:在application.properties文件中配置数据源信息。 ```properties spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 3. 创建实体类:创建与数据库中对应的Java实体类,并使用JPA注解进行配置。 ```java @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @Column(name = "age") private Integer age; // getter、setter方法 } ``` 4. 创建Repository接口:创建一个继承自JpaRepository的接口。 ```java public interface UserRepository extends JpaRepository<User, Long> { } ``` 5. 启动应用程序:启动Spring Boot应用程序,Hibernate自动根据实体类和数据源配置自动生成结构。 以上就是使用Spring Boot、JPA和Hibernate生成的基本步骤。需要注意的是,Hibernate自动生成结构可能不完全符合我们的要求,需要根据实际情况进行微调和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值