动态类型种子弹簧路径变量

时间:2018-06-01 17:16:35

标签: spring spring-mvc spring-boot spring-rest

我计划用JPA创建一个简单的Spring Rest服务项目,它将根据路径变量中给出的实体名称和实体ID从数据库中获取详细信息。

考虑以下代码。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ds.dao.EntityDAO;
import com.ds.entities.Employees;

import javax.persistence.Entity;
@Controller
@RequestMapping("/")
public class DynaRestController {

@Autowired
EntityDAO entityDAO;


@RequestMapping(value = "{entityName}/{enityId}",method = RequestMethod.GET)
public @ResponseBody Object getEntity(@PathVariable("entityName") String entityName,@PathVariable("enityId") Object id) {
    return entityDAO.getEntityById(entityName, id);
}

}

实体DAO类

public class EntityDAO {
@Autowired
EntityManager entityManager;


public Object getEntityById(String entityName, Object id) {
    EntityType<?> entityType = getEntityByName(entityName);
    Object idcasted = entityType.getIdType().getJavaType().cast(id);
    System.out.println(idcasted.getClass().getName());
    Object entity = entityManager.find(entityType.getJavaType(), idcasted);
    System.out.println("Entity.. Name .." + entityName);
    // Employees entity = session.load(Employees.class, id);
    return entity;

}

private EntityType<?> getEntityByName(String name) {
    Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
    for (Iterator<EntityType<?>> iterator = entities.iterator(); iterator.hasNext();) {
        EntityType<?> entityType = (EntityType<?>) iterator.next();
        if (entityType.getName().equals(name))
            return entityType;
    }

    return null;
}

}

员工类

@Configurable
@Entity
@Table(name = "employees", catalog = "employees")
public class Employees implements java.io.Serializable {

/**
 * 
 */
private static final long serialVersionUID = 1L;
private int empNo;
private Date birthDate;
private String firstName;
private String lastName;
private String gender;
private Date hireDate;
private Set<Titles> titleses = new HashSet<Titles>(0);
private Set<Salaries> salarieses = new HashSet<Salaries>(0);
private Set<DeptEmp> deptEmps = new HashSet<DeptEmp>(0);
private Set<DeptManager> deptManagers = new HashSet<DeptManager>(0);

public Employees() {
}

public Employees(int empNo, Date birthDate, String firstName, String lastName, String gender, Date hireDate) {
    this.empNo = empNo;
    this.birthDate = birthDate;
    this.firstName = firstName;
    this.lastName = lastName;
    this.gender = gender;
    this.hireDate = hireDate;
}

public Employees(int empNo, Date birthDate, String firstName, String lastName, String gender, Date hireDate,
        Set<Titles> titleses, Set<Salaries> salarieses, Set<DeptEmp> deptEmps, Set<DeptManager> deptManagers) {
    this.empNo = empNo;
    this.birthDate = birthDate;
    this.firstName = firstName;
    this.lastName = lastName;
    this.gender = gender;
    this.hireDate = hireDate;
    this.titleses = titleses;
    this.salarieses = salarieses;
    this.deptEmps = deptEmps;
    this.deptManagers = deptManagers;
}

@Id
@Column(name = "emp_no", unique = true, nullable = false)
public int getEmpNo() {
    return this.empNo;
}

public void setEmpNo(int empNo) {
    this.empNo = empNo;
}

@Temporal(TemporalType.DATE)
@Column(name = "birth_date", nullable = false, length = 10)
public Date getBirthDate() {
    return this.birthDate;
}

public void setBirthDate(Date birthDate) {
    this.birthDate = birthDate;
}

@Column(name = "first_name", nullable = false, length = 14)
public String getFirstName() {
    return this.firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

@Column(name = "last_name", nullable = false, length = 16)
public String getLastName() {
    return this.lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

@Column(name = "gender", nullable = false, length = 2)
public String getGender() {
    return this.gender;
}

public void setGender(String gender) {
    this.gender = gender;
}

@Temporal(TemporalType.DATE)
@Column(name = "hire_date", nullable = false, length = 10)
public Date getHireDate() {
    return this.hireDate;
}

public void setHireDate(Date hireDate) {
    this.hireDate = hireDate;
}

@OneToMany(fetch = FetchType.LAZY, mappedBy = "employees")
public Set<Titles> getTitleses() {
    return this.titleses;
}

public void setTitleses(Set<Titles> titleses) {
    this.titleses = titleses;
}

@OneToMany(fetch = FetchType.LAZY, mappedBy = "employees")
public Set<Salaries> getSalarieses() {
    return this.salarieses;
}

public void setSalarieses(Set<Salaries> salarieses) {
    this.salarieses = salarieses;
}

@OneToMany(fetch = FetchType.LAZY, mappedBy = "employees")
@JsonBackReference
public Set<DeptEmp> getDeptEmps() {
    return this.deptEmps;
}

public void setDeptEmps(Set<DeptEmp> deptEmps) {
    this.deptEmps = deptEmps;
}

@OneToMany(fetch = FetchType.LAZY, mappedBy = "employees")
public Set<DeptManager> getDeptManagers() {
    return this.deptManagers;
}

public void setDeptManagers(Set<DeptManager> deptManagers) {
    this.deptManagers = deptManagers;
}

}

当我使用以下代码

动态转换路径变量时
Object idcasted = entityType.getIdType().getJavaType().cast(id);
Object entity = entityManager.find(entityType.getJavaType(), idcasted);

它正在抛出ClassCastExpcetion

java.lang.ClassCastException:无法将java.lang.String强制转换为int     在java.lang.Class.cast(Class.java:3369)〜[na:1.8.0_112]     在com.techm.att.ds.dao.EntityDAO.getEntityById(EntityDAO.java:33)〜[classes /:na]     在com.techm.att.ds.dao.EntityDAO $$ FastClassBySpringCGLIB $$ 8e64d745.invoke()〜[classes /:na]     在org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)〜[spring-core-4.3.13.RELEASE.jar:4.3.13.RELEASE]     在org.springframework.aop.framework.CglibAopProxy $ CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)〜[spring-aop-4.3.13.RELEASE.jar:4.3.13.RELEASE]     在org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)〜[spring-aop-4.3.13.RELEASE.jar:4.3.13.RELEASE]     在org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)〜[spring-tx-4.3.13.RELEASE.jar:4.3.13.RELEASE]     在org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)〜[spring-aop-4.3.13.RELEASE.jar:4.3.13.RELEASE]

任何帮助都会受到高度关注..

1 个答案:

答案 0 :(得分:0)

我写了一个关于评论的简单例子。 这是相同的行为。你的RestController实际上是一个字符串:

  public static void main(String[] args) {
    Object myString = "myString";
    System.out.println(myString.getClass()); // class java.lang.String
    int.class.cast(myString);
}

cast方法检查您给定值的实例,但它失败了:

 public T cast(Object obj) {
    if (obj != null && !isInstance(obj))
        throw new ClassCastException(cannotCastMsg(obj));
    return (T) obj;
}