【发布时间】:2020-02-23 18:19:46
【问题描述】:
问题:当我通过 bash 控制台发出发布请求时,会创建一个新表。其余查询转到新表。 比他不喜欢那些可用的数据库。据我了解-他们只是不知道,但我不知道如何正确引导它。虽然所有变量也都被命名了。
发现由于 Message 类中的 Entity 注释而产生了问题。请告诉我如何将其添加到现有表中,尝试@Table(name = "ApiTable") 到现有表中,它会生成一个新的 api_table.. 也不太明白需要添加/更改什么来接受 json 发布请求。
应用
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@EnableJpaRepositories("com.example.api")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
主控制器
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 TestApi;
@PostMapping(path="/add")
public @ResponseBody String addNewUser (@RequestParam String name
, @RequestParam String email) {
Message n = new Message();
n.setName(name);
n.setEmail(email);
TestApi.save(n);
return "Saved";
}
@GetMapping(path="/all")
public @ResponseBody Iterable<Message> getAllUsers() {
return TestApi.findAll();
}
}
留言
import javax.persistence.*;
@Entity
public class Message {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String email;
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;
}
}
用户存储库
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<Message, Integer> {
}
application.properties
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost/Test?useUnicode=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
【问题讨论】:
-
您希望 Hibernate 更新您的数据库架构吗?现有表的名称是什么?
-
是的,我希望 Hibernate 更新已经存在的数据库。它的名字是TestApi,表的名字是ApiTable
-
“它的名字是 TestApi” - 我不确定“它”是什么,因为我只询问了表的名称,而您说一个名为“ApiTable”。
-
对不起,表名是ApiTable
-
我明白了。问题似乎是您必须替换的 Spring Boot 的默认命名策略。在这里查看一些信息:stackoverflow.com/questions/39162976/…
标签: java spring-boot