SpringBoot jpa 动态表名查询咋写
时间: 2024-02-17 10:33:21 浏览: 209
在SpringBoot中使用JPA动态表名查询的方法如下:
1. 定义一个接口,在接口中使用@Query注解定义动态表名查询语句,例如:
```
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM #{#tableName} WHERE id = ?1", nativeQuery = true)
User findByTableName(Long id, String tableName);
}
```
2. 在实现类中,使用SpEL表达式传入动态表名,例如:
```
public class UserRepositoryImpl implements UserRepositoryCustom {
@PersistenceContext
private EntityManager entityManager;
@Override
public User findByTableName(Long id, String tableName) {
Query query = entityManager.createNativeQuery("SELECT * FROM " + tableName + " WHERE id = ?", User.class);
query.setParameter(1, id);
return (User) query.getSingleResult();
}
}
```
3. 在Service中调用动态表名查询方法,例如:
```
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User findByTableName(Long id, String tableName) {
return userRepository.findByTableName(id, tableName);
}
}
```
这样就可以实现在SpringBoot中使用JPA动态表名查询了。
阅读全文
相关推荐


















