插入多对一关系

时间:2016-10-04 12:04:19

标签: json spring web-services spring-boot spring-data-jpa

嘿,大家我有2节课

Admins.java

package com.spark.entites;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;


import com.fasterxml.jackson.annotation.JsonView;
import com.spark.View;

@Entity
public class Admins {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonView(View.all.class)
private int idu;
@JsonView(View.all.class)
private String logins;
@JsonView(View.all.class)
private String password;
@JsonView(View.all.class)
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
@JoinColumn(name = "idr")
private Role role;

public int getIdu() {
    return idu;
}

public void setIdu(int idu) {
    this.idu = idu;
}

public String getLogins() {
    return logins;
}

public void setLogins(String logins) {
    this.logins = logins;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}



public Admins(int idu, String logins, String password, Role role) {
    super();
    this.idu = idu;
    this.logins = logins;
    this.password = password;
    this.role = role;
}

public Admins() {
    super();
}

}

和Role.java

@Entity
public class Role {


@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@JsonView(View.all.class)
private int idr ; 
@JsonView(View.all.class)
private String role ;
public int getIdr() {
    return idr;
}
public void setIdr(int idr) {
    this.idr = idr;
}
public String getRole() {
    return role;
}
public void setRole(String role) {
    this.role = role;
}
public Role(int idr, String role) {
    super();
    this.idr = idr;
    this.role = role;
}
public Role() {
    super();
} 

你可以看到我和这个2 classess有一个manyToOne关系,我正在使用spring-boot我有这样的存储库:

public interface AdminRepository extends JpaRepository<Admins, Integer>{
}

并在控制器中:

@RestController
public class AdminsController {

@Autowired
AdminRepository adminRepository;

// this one to load R
@JsonView(View.all.class)
@RequestMapping(value = "/Admins/load")
public List<Admins> load() {
    return adminRepository.findAll();
}

@RequestMapping(value = "/Admins/insert")
public void insertusers(Admins a) {
    adminRepository.save(a);
}

}

在我的控制器中,当我尝试插入像这样的idr值时,我有2个函数加载,1个插入:

http://localhost:8080/Admins/insert?logins=yosra&password=yossra&role.idr=1

我获得了角色null的价值

{
idu: 23,
logins: "yosra",
password: "yossra",
role: null
} 

这假设是这样的:

{
idu: 3,
logins: "bassem",
password: "admin",
role: {
idr: 1,
role: "Admin"
}
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

尝试在role中为字段Admins.class添加getter和setter,或者为access = AccessType.FIELD的注释@Entity添加属性Admins.class