简体   繁体   中英

Java Spring Boot adds random “d” character on SQL query

I am making a user administration platform with spring boot. When I make a GET request to return the users I get this error

There was an unexpected error (type=Internal Server Error, status=500). could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet... Caused by: java.sql.SQLSyntaxErrorException: Unknown column 'user0_.dtype' in 'field list'

What is that random 'dtype' column?

Edit: I changed the "type" to "role" because it is very confusing. I also noticed that even when I change it in my code, I still get the same error. The question has been edited accordingly.

Entity

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "users")
public class User {
    @Id
    @Column(name = "id")
    private int id;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;
    @Column(name = "username")
    private String username;
    @Column(name = "password")
    private String password;
    @Column(name = "role")
    private String role;
    
    public User() {}
    
    public User(String firstName, String lastName, String username, String password, String role) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.username = username;
        this.password = password;
        this.role = role;
    }

    public String getFirstName() {
        return firstName;
    }

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

    public String getLastName() {
        return lastName;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public int getId() {
        return id;
    }

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

    public String getPassword() {
        return password;
    }

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

    @Override
    public String toString() {
        return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", username=" + username
                + ", password=" +password+ ", role=" + role + "]";
    }
}

Controller

@RestController
public class UserController {

    @Autowired
    private UserRepository userRepository;
    
    @GetMapping("/users")
    public List<User> retrieveAllUsers(){
        return userRepository.findAll();
    }
    
    @GetMapping("/users/{id}")
    public User retreiveTask(@PathVariable int id) {
        Optional<User> user = userRepository.findById(id);
        
        return user.get();
    }
    
    @DeleteMapping("/users/{id}")
    public void deleteUser(@PathVariable int id) {
        userRepository.deleteById(id);
    }
    
    @PostMapping("/users")
    public ResponseEntity<Object> createUser(@RequestBody User user){
        User savedUser = userRepository.save(user);
        
        URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
                .buildAndExpand(savedUser.getId()).toUri();
        
        return ResponseEntity.created(location).build();
    }
    
    @PutMapping("/users/{id}")
    public ResponseEntity<Object> updateUser(@RequestBody User user, @PathVariable int id){
        Optional<User> userOptional = userRepository.findById(id);
        
        if(!userOptional.isPresent())
            return ResponseEntity.notFound().build();
        user.setId(id);
        
        userRepository.save(user);
        return ResponseEntity.noContent().build();
    }
}

MySQL Database Script

CREATE TABLE users (
  id int(11) NOT NULL AUTO_INCREMENT,
  first_name varchar(100) NOT NULL,
  last_name varchar(100) NOT NULL,
  username varchar(100) NOT NULL,
  password varchar(100) NOT NULL,
  role text NOT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

Any help would be appreciated.

d is for data; user data type. you also have the id set to AUTO_INCREMENT, which means you need to declare it at the class level by adding this @GeneratedValue(strategy = GenerationType.IDENTITY):

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

@GetMapping(path = "User")
public ResponseEntity<List<User>> getAllUsers(){
    
    Optional<List<User>> optUsers = Optional.ofNullable(userRepo.findAll());
    
    if(optUsers.isPresent()) {
        List<User> Users = optUsers.get();
        
        return new ResponseEntity<List<User>>(Users, HttpStatus.OK);
    } else {
        return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
    }
}

https://www.viralpatel.net/hibernate-inheritence-table-per-hierarchy-mapping/

If the @DiscriminatorColumn annotation is missing, and a discriminator column is required, the name of the discriminator column defaults to "DTYPE" and the discriminator type to DiscriminatorType.STRING.

I found the problem. I didn't mention that the User class is a superclass to a few classes on my project since I believed that was irrelevant. Spring doesm't it like when Entity classes act as superclass. So I just had to remove the annotations and instead add the annotation "@MappedSuperclass".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM