多对多的关系"专栏不存在" Hibernate& Springboot

时间:2016-06-05 14:11:15

标签: java spring hibernate

我使用spring和hibernate编写第一个app我遇到了很多关系问题。当我执行代码时,它会给我一个错误:列subject0_.subject_name不存在。这对我来说很奇怪,因为我的桌子被称为主题而不是主题0。 在我的"类"的代码下面类

@Entity
public class Class {
@NotNull
@Id
@Column(name = "class_name")
private String name;

@Column(name = "start_year")
private int startYear;


@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "Class_has_Subject", joinColumns = {@JoinColumn(name = "class_name")}, inverseJoinColumns = {@JoinColumn(name = "subject_name")})
private Set<Subject> subject = new HashSet<Subject>(0);

public Set<Subject> getSubject() {
    return this.subject;
}


public void setSubject(Set<Subject> subject) {
    this.subject = subject;
}

public int getStartYear() {
    return startYear;
}

public void setStartYear(int startYear) {
    this.startYear = startYear;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Class() {
}


} 

学科分类:

@Entity(name = "subject")

public class Subject {

 @NotNull
@Id
@Column(name = "subject_name")
private String name;
@Column(name = "teacher")
private String teacher;
public Subject(String name, String teacher) {
    this.name = name;
    this.teacher = teacher;
}

public Subject() {
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getTeacher() {
    return teacher;
}
public void setTeacher(String teacher) {
    this.teacher = teacher;
}
}

ClassRepository接口:

public interface ClassRepository extends CrudRepository<Class,String> {
List<Class> findByName(String name);
}

Classcontroller类:

@Controller

@EnableAutoConfiguration

public class ClassController {

@Autowired
ClassRepository repo;

@RequestMapping(value = "/class/get/{name}/", method = RequestMethod.GET)
@ResponseBody
public Set<Subject> getClass(@PathVariable String name) {

    Class a= repo.findByName(name).get(0);
    System.out.println(a.getStartYear());
    Set<Subject> s=a.getSubject();
    return s;

}

2 个答案:

答案 0 :(得分:1)

subject0_是hibernate为您的表提供的名称。它不是表的实际名称。因此,当hibernate尝试查询您的类表时,它将构造一个类似于以下

的sql命令
select
        class0_.class_name as class_na1_2_,
        class0_.start_year as start_ye2_2_ 
    from
        public.class class0_ 
    where
        class0_.class_name=?

注意&#34; class0 _&#34;是&#34;类&#34;的引用;表

如果您使用的是spring boot,可以通过在application.properties中添加以下两行来配置hibernate以记录这些sql命令以进行调试。

spring.jpa.properties.hibernate.show_sql = true
spring.jpa.properties.hibernate.format_sql = true

其他环境将是他们配置hibernate的方法。

那就是说,你的映射似乎没有任何问题。我的预感是你的主题表没有&#34; subject_name&#34;列,因为您错过了手动添加它,或者在您启动应用程序时hibernate无法添加它。

如果您希望hibernate根据您的实体定义更新表,则可以使用其hbm2ddl功能。要在Spring Boot应用程序中执行此操作,您应该在application.properties中包含以下行:

spring.jpa.properties.hibernate.hbm2ddl.auto = update

答案 1 :(得分:-1)

检查您的ManyToMany地图主题