我试图使用SpringBoot,Java,Mysql制作CRUD RESTapi。我的代码可以运行并且可以在Eclipse中运行,但是当我尝试将数据从POST Man POST到mysql workbench时,总是显示错误。
项目名称:SpringRestfulWebServiceHibernate 我的pom.xml文件:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>springmvc_example</groupId>
<artifactId>SpringRestfulWebServiceHibernate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Problem in POSTMAN
POST:localhost:8080 / SpringRestfulWebServiceHibernate / add / 每次都会显示此错误消息:
{
"timestamp": 1567422726395,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/SpringRestfulWebServiceHibernate/add/"
}
Main Project codes:
src/main/java:
package: springmvc_example.application
class: UserApplication.java
package springmvc_example.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class UserApplication {
public static void main(String[]args) {
SpringApplication.run(UserApplication.class, args);
}
}
Codes for configuration.
Package: springmvc_example.config
class: HibernateConfig.java
package springmvc_example.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@ComponentScan({ "springmvc_example.config" })
public class HibernateConfig {
@Bean
public LocalSessionFactoryBean sessionFactoryBean(){
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(new String[] { "springmvc_example.model" });
sessionFactoryBean.setHibernateProperties(hibernateProperties());
return sessionFactoryBean;
}
@Bean
public DataSource dataSource(){
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/springrestful");
ds.setUsername("root");
ds.setPassword("djhonseena");
return ds;
}
private Properties hibernateProperties(){
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "false");
return properties;
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s){
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
Another configuration class:
WebConfig.java
package springmvc_example.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@EnableWebMvc
@ComponentScan({"springmvc_example"})
public class WebConfig {
}
Webinitializer configuration class:
WebInitializer.java
package springmvc_example.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class[] getRootConfigClasses() {
return new Class[]{ WebConfig.class };
}
@Override
protected Class[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[]{ "/" };
}
}
控制器包和类
package: springmvc_example.controller
class: UserController.java
package springmvc_example.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import springmvc_example.model.User;
import springmvc_example.service.UserService;
@RestController
public class UserController {
@Autowired
UserService userService;
@RequestMapping(value="/user/", method=RequestMethod.GET, headers="Accept=application/json")
public @ResponseBody List getListUser(){
List users = userService.getListUser();
return users;
}
@RequestMapping(value="/add/", method=RequestMethod.POST)
public @ResponseBody User add(@RequestBody User user){
userService.saveOrUpdate(user);
return user;
}
@RequestMapping(value="/update/{id}", method=RequestMethod.PUT)
public @ResponseBody User update(@PathVariable("id") int id, @RequestBody User user){
user.setId(id);
userService.saveOrUpdate(user);
return user;
}
@RequestMapping(value="/delete/{id}", method=RequestMethod.DELETE)
public @ResponseBody User delete(@PathVariable("id") int id){
User user = userService.findUserById(id);
userService.deleteUser(id);
return user;
}
}
数据库包和类:
package: springmvc_example.dao
interface: UserDao.java
package springmvc_example.dao;
import java.util.List;
import springmvc_example.model.User;
public interface UserDao {
public List getListUser();
public void saveOrUpdate(User user);
public void deleteUser(int id);
public User findUserById(int id);
}
另一个数据库类
类:UserDaoImpl.java 软件包springmvc_example.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import springmvc_example.model.User;
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private SessionFactory sessionFactory;
protected Session getSession(){
return sessionFactory.getCurrentSession();
}
@SuppressWarnings("unchecked")
public List getListUser() {
Criteria criteria = getSession().createCriteria(User.class);
return (List) criteria.list();
}
public void saveOrUpdate(User user) {
getSession().saveOrUpdate(user);
}
public void deleteUser(int id) {
User user = (User) getSession().get(User.class, id);
getSession().delete(user);
}
public User findUserById(int id) {
return (User) getSession().get(User.class, id);
}
}
模型包和类:
package: springmvc_example.model
class: User
package springmvc_example.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private int id;
@Column(name="name", nullable=true)
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package: springmvc_example.service
interface: UserService.java
package springmvc_example.service;
import java.util.List;
import springmvc_example.model.User;
public interface UserService {
public List getListUser();
public void saveOrUpdate(User user);
public void deleteUser(int id);
public User findUserById(int id);
}
class: UserServiceImpl.java
package springmvc_example.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springmvc_example.dao.UserDao;
import springmvc_example.model.User;
@Service
@Transactional
public class UserServiceImpl implements UserService {
UserDao userDao;
@Autowired
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public List getListUser() {
return userDao.getListUser();
}
public void saveOrUpdate(User user) {
userDao.saveOrUpdate(user);
}
public void deleteUser(int id) {
userDao.deleteUser(id);
}
public User findUserById(int id) {
return userDao.findUserById(id);
}
}
用于mysql数据库连接的属性文件
src/main/resources
application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springrestful
spring.datasource.username=root
spring.datasource.password=djhonseena
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false
spring.jpa.properties.hibernate.format_sql = true
spring.datasource.validationQuery=SELECT 1
spring.datasource.testOnBorrow=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
答案 0 :(得分:0)
将您的请求发布到localhost:8080/add/
否则,添加一个类级别@RequestMapping
注释,指定端点的value
。
答案 1 :(得分:0)
Spring Boot在/
的上下文中初始化应用程序。没有任何映射到/SpringRestfulWebServiceHibernate
。
要使您的请求正常运行,只需将POST发送至/add/
。 (由于您已在add /的末尾添加了斜杠,因此必须使用此斜杠(/ add /)进行发送。)
现在,如果您需要在请求中使用/SpringRestfulWebServiceHibernate
的上下文,只需将以下行放在application.properties
中:
server.servlet.context-path=/SpringRestfulWebServiceHibernate