【问题标题】:jpa @Inheritance(strategy=InheritanceType.JOINED) how to select super entity not contain childjpa @Inheritance(strategy=InheritanceType.JOINED) 如何选择不包含子实体的超级实体
【发布时间】:2017-03-23 08:28:01
【问题描述】:

我有一个问题:假设我有两个类 User 和 person,person 扩展了 User。在用户中我有@Inheritance(strategy=InheritanceType.JOINED)。有时我只想选择不包含子表信息的用户信息,

User.java(超类)

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name = "user_type")
@Table(name = "users")
public class User {.........}

Person.java

@Entity
public class Person extends User {......}

公司.java

@Entity
public class Company extends User {.............}

UserRepository.java

@Transactional
public interface UserRepository extends UserBaseRepository<User> {

//@Query(value="select u from User u where u.email=?1")
@Query(value="select u.id,u.email from User u where u.email=?1")
User getUser(String email);

@Query("select u from User u where u.email=?1")
User getUser2(String email);

@Query(value="select * from Users where email=:email",nativeQuery=true)
User getUser3(String email);
}

出现以下异常:

Hibernate: select user0_.id as col_0_0_, user0_.email as col_1_0_ from users user0_ where user0_.email=?
org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.Object[] to type netgloo.models.User for value '{1, 635@qq.com}';
nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type java.lang.Long to type netgloo.models.User
  1. 如何获取不包含 Person,Company 的用户信息
  2. 如何获取不包含用户、公司的人员信息

【问题讨论】:

    标签: spring-data-jpa


    【解决方案1】:

    要仅选择用户,您可以使用 JPQL TYPE() 运算符,如下所示:

    SELECT u FROM User u WHERE TYPE(u) := User

    这里是完整的解释:https://stackoverflow.com/a/3766541/534877

    【讨论】:

    • @Query(value="select u from User u where TYPE(u) Person and u.email=?1")
    • @Query(value="select u from User u where TYPE(u) Person and u.email=?1")
    • 选择 user0_.id 作为 id2_1_,user0_.email 作为 email3_1_,user0_1_.first_name 作为 first_na1_0_,user0_1_.last_name 作为 last_nam2_0_,user0_.user_type 作为 user_typ1_1_ 从用户 user0_ 离开外连接人 user0_1_ 在 user0_.id =user0_1_.id where case when user0_1_.id is not null then Person when user0_.id is not null then 'User' end 'Person' and user0_.email=?
    • 在spring jpa中type(u)不能生效
    • 从查询sql中可以看出还有使用left jon,不只是选择父表,比如select * from user;
    猜你喜欢
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多