1
大家好,我有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();
}
,你可以看到我有一個manyToOne
關係這2 classess,正在使用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);
}
}
在我的控制器
我有2個功能,一個加載和一個插入當我嘗試插入IDR值是這樣的:
http://localhost:8080/Admins/insert?logins=yosra&password=yossra&role.idr=1
我得到的值
:角色無效{
idu: 23,
logins: "yosra",
password: "yossra",
role: null
}
這是假設是這樣的
{
idu: 3,
logins: "bassem",
password: "admin",
role: {
idr: 1,
role: "Admin"
}
}
感謝任何幫助。