Nested exception is java.lang.ClassCastException: java.lang.String cannot be cast

huangapple go评论80阅读模式
英文:

Nested exception is java.lang.ClassCastException: java.lang.String cannot be cast

问题

我对Spring Data还不熟悉,我有这个错误java.lang.String不能转换为com.example.accessingdatamysql.User,不知道怎么修复它!我添加了代码的各个相关部分。

Main.Controller

package com.example.accessingdatamysql;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller 
@RequestMapping(path="/demo") 
public class MainController {
  @Autowired 
  private UserRepository userRepository;

  @Transactional
  @PostMapping(path="/add")
  public @ResponseBody String addNewUser (@RequestParam String name,
          @RequestParam String email, @RequestParam String surname) 
  {
      User n = new User();
      n.setName(name);
      n.setSurname(surname);
      n.setEmail(email);
      userRepository.create(n);
	  return "Saved";
  }

  @GetMapping(path="first")
  User one(@RequestParam String name) {
      return userRepository.findFirstByName(name);
  }
}  

User.java

package com.example.accessingdatamysql;

import java.sql.Timestamp;
import java.time.Instant;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity 
public class  User {
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Integer id;
 
  private String name;

  private String email;
  
  private String surname;
  
  @Column(name="stmp", columnDefinition = "TIMESTAMP (6)")
  Timestamp timestamp = Timestamp.from(Instant.now());

  public void setTimestamp(Timestamp timestamp) {
      this.timestamp = timestamp;
  }

  public Timestamp getTimestamp() {
      return timestamp;
  }

  public String getSurname() {
      return surname;
  }
 
  public void setSurname(String surname) {
	  this.surname = surname;
  }
 
  public Integer getId() {
      return id;
  }

  public void setId(Integer id) {
      this.id = id;
  }

  public String getName() {
      return name;
  }

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

  public String getEmail() {
      return email;
  }

  public void setEmail(String email) {
      this.email = email;
  }
}

RepoImpl.java

package com.example.accessingdatamysql;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Component;

@Component
public class UserRepositoryImpl implements UserRepository {
	
	private final EntityManager em;
	
	public UserRepositoryImpl(EntityManager entityManager) {
		this.em = entityManager;
	}

	@Override
	public User findFirstByName(String name) {
		CriteriaBuilder builder = em.getCriteriaBuilder();
		CriteriaQuery<User> criteria = builder.createQuery(User.class);
		Root<User> root = criteria.from(User.class);
		criteria.select(root.get("name"));
		criteria.orderBy(builder.asc(root.get("timestamp")));
		TypedQuery<User> query = em.createQuery(criteria).setMaxResults(1);
		return query.getSingleResult();
	}
	
	@Override
	public void create(User entity) {
		em.persist(entity);	
	}   
}

错误

[处理请求失败;根本原因是java.lang.ClassCastException: 无法将java.lang.String转换为com.example.accessingdatamysql.User],根本原因
java.lang.ClassCastException: 无法将java.lang.String转换为com.example.accessingdatamysql.User
在com.example.accessingdatamysql.UserRepositoryImpl.findFirstByName(UserRepositoryImpl.java:35) ~[classes!/:0.0.1-SNAPSHOT]
英文:

I am new to spring-data, I have this error java.lang.String cannot be cast to com.example.accessingdatamysql.User and do not know how to fix it! I add the various relevant parts of my code.

The method should output the oldest entry (via timestamp) by name.

Main.Controller

package com.example.accessingdatamysql;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller 
@RequestMapping(path=&quot;/demo&quot;) 
public class MainController {
@Autowired 
private UserRepository userRepository;
@Transactional
@PostMapping(path=&quot;/add&quot;)
public @ResponseBody String addNewUser (@RequestParam String name,
@RequestParam String email,@RequestParam String surname) 
{
User n = new User();
n.setName(name);
n.setSurname(surname);
n.setEmail(email);
userRepository.create(n);
return &quot;Saved&quot;;
}
@GetMapping(path=&quot;first&quot;)
User one(@RequestParam String name) {
return userRepository.findFirstByName(name);
}
}  

User.java

package com.example.accessingdatamysql;
import java.sql.Timestamp;
import java.time.Instant;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity 
public class  User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
public String name;
private String email;
private String surname;
@Column(name=&quot;stmp&quot;, columnDefinition = &quot;TIMESTAMP (6)&quot;)
Timestamp timestamp = Timestamp.from(Instant.now());
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
public Timestamp getTimestamp() {
return timestamp;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

RepoImpl.java

package com.example.accessingdatamysql;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Component;
@Component
public class UserRepositoryImpl implements UserRepository {
private final EntityManager em;
public UserRepositoryImpl(EntityManager entityManager) {
this.em = entityManager;
}
@Override
public User findFirstByName(String name) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery&lt;User&gt; criteria = builder.createQuery(User.class);
Root&lt;User&gt; root = criteria.from(User.class);
criteria.select(root.get(&quot;name&quot;));
criteria.orderBy(builder.asc(root.get(&quot;timestamp&quot;)));
TypedQuery&lt;User&gt; query = em.createQuery(criteria).setMaxResults(1);
return query.getSingleResult();
}
@Override
//	per la creazione//
public void create(User entity) {
em.persist(entity);	
}   
}

ERROR

 [Request processing failed; nested exception is java.lang.ClassCastException: java.lang.String cannot be cast to com.example.accessingdatamysql.User] with root cause
java.lang.ClassCastException: java.lang.String cannot be cast to com.example.accessingdatamysql.User
at com.example.accessingdatamysql.UserRepositoryImpl.findFirstByName(UserRepositoryImpl.java:35) ~[classes!/:0.0.1-SNAPSHOT]

答案1

得分: 1

如果你想通过名称查找 User,你应该将过滤参数设置在 criteria.where 中,而不是在 criteria.select 中:

public User findFirstByName(String name) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<User> criteria = builder.createQuery(User.class);
    Root<User> root = criteria.from(User.class); // root 是 User
    criteria.select(root).where(builder.equal(root.get("name"), name));
    criteria.orderBy(builder.asc(root.get("timestamp")));
    TypedQuery<User> query = em.createQuery(criteria).setMaxResults(1);
    return query.getSingleResult();
}

然而,criteria.select(root.get("name")); 意味着只选择和返回 &quot;name&quot; 列,即应返回第一个用户的名称。

如果需要这样的信息,可以按以下方式检索:

public String findFirstUserName() {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<String> criteria = builder.createQuery(String.class);
    Root<User> root = criteria.from(User.class); // root 是 User
    criteria.select(root.get("name"));  // 获取名称
    criteria.orderBy(builder.asc(root.get("timestamp"))); // 第一个/最早的用户的名称
    TypedQuery<String> query = em.createQuery(criteria).setMaxResults(1);
    return query.getSingleResult();
}
英文:

If you meant to find User by name, you should have set the filter parameter not in criteria.select but in criteria.where:

public User findFirstByName(String name) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery&lt;User&gt; criteria = builder.createQuery(User.class);
    Root&lt;User&gt; root = criteria.from(User.class); // root is User
    criteria.select(root).where(builder.equal(root.get(&quot;name&quot;), name));
    criteria.orderBy(builder.asc(root.get(&quot;timestamp&quot;)));
    TypedQuery&lt;User&gt; query = em.createQuery(criteria).setMaxResults(1);
    return query.getSingleResult();
}

While criteria.select(root.get(&quot;name&quot;)); implies that only column &quot;name&quot; is selected and returned, that is the name of the first user should be returned.

If such information is needed, it may be retrieved in the following way:

public String findFirstUserName() {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery&lt;String&gt; criteria = builder.createQuery(String.class);
    Root&lt;User&gt; root = criteria.from(User.class); // root is User
    criteria.select(root.get(&quot;name&quot;));  // getting name 
    criteria.orderBy(builder.asc(root.get(&quot;timestamp&quot;))); // of the first/earliest user 
    TypedQuery&lt;String&gt; query = em.createQuery(criteria).setMaxResults(1);
    return query.getSingleResult();
}

答案2

得分: 0

按照错误提示所说的做:

CriteriaQuery<String> criteria = builder.createQuery(String.class);

而不是:

CriteriaQuery<User> criteria = builder.createQuery(User.class);

在这里阅读更多参考资料

英文:

Do just like the error says -

CriteriaQuery&lt;String&gt; criteria = builder.createQuery(String.class);

instead of

CriteriaQuery&lt;User&gt; criteria = builder.createQuery(User.class);

Read more here Reference

huangapple
  • 本文由 发表于 2020年10月2日 00:00:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64159065.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定