jpa mysql 表名 前缀,JPA(休眠)和自定义表前缀

Is it possible to override table names in JPA/Hibernate in order to add a common prefix for all project entities? For instance to be able to prefix all JBPM 5 tables by "JBPM5_" prefix.

Example for the accepted answer:

public class JBPM5NamingStrategy extends ImprovedNamingStrategy {

public String classToTableName(String className) {

return StringHelper.unqualify(className);

}

public String propertyToColumnName(String propertyName) {

return propertyName;

}

public String tableName(String tableName) {

return "JBPM5_" + tableName;

}

public String columnName(String columnName) {

return columnName;

}

public String propertyToTableName(String className, String propertyName) {

return "JBPM5_" + classToTableName(className) + '_'

+ propertyToColumnName(propertyName);

}

}

解决方案

One way to rename all tables at once, is to implement your own namingStrategy (implementation of org.hibernate.cfg.NamingStrategy).

The NamingStrategy used is specified within persistence.xml by

value="com.example.MyNamingStrategy" />

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中使用JPA动态表名需要使用DSL(Domain Specific Language)查询来实现。DSL查询是一种基于对象的查询语言,可以根据运行时条件生成动态的SQL查询。 要实现动态表名,首先需要定义一个通用的实体类,该实体类包含了所有可能的字段。然后根据运行时条件,使用DSL查询构建动态的表名。 以下是一个示例,演示了如何在Spring Boot中使用JPA动态表名: 1. 定义通用的实体类: ```java @Entity @Table(name = "generic_table") public class GenericEntity { // 定义通用的字段 @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; // 其他字段... // getter和setter方法 } ``` 2. 创建动态表名的接口: ```java public interface DynamicTableName { @Query(value = "SELECT * FROM :tableName", nativeQuery = true) List<GenericEntity> findByDynamicTableName(@Param("tableName") String tableName); } ``` 3. 创建实现动态表名接口的类: ```java @Repository public class DynamicTableNameImpl implements DynamicTableName { @PersistenceContext private EntityManager entityManager; @Override public List<GenericEntity> findByDynamicTableName(String tableName) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<GenericEntity> query = criteriaBuilder.createQuery(GenericEntity.class); Root<GenericEntity> root = query.from(GenericEntity.class); // 动态设置表名 root.alias(tableName); query.select(root); TypedQuery<GenericEntity> typedQuery = entityManager.createQuery(query); return typedQuery.getResultList(); } } ``` 4. 在Service或Controller中使用动态表名查询: ```java @Service public class YourService { @Autowired private DynamicTableName dynamicTableName; public List<GenericEntity> findByDynamicTableName(String tableName) { return dynamicTableName.findByDynamicTableName(tableName); } } ``` 在以上示例中,通过将动态表名作为参数传递给findByDynamicTableName()方法,可以实现根据不同的条件查询不同的。注意,这里使用了原生查询(nativeQuery = true)来执行SQL查询。 希望以上示例对你有帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值