我目前正在使用Hibernate学习Spring。我有一个简单的客户表,其中的列是“ ID”,“ first_name”,“ last_name”,“ email” ..
我使用休眠模式查询数据库并列出所有客户的结果作为输出。我已经将Spring boot和MVC一起使用了。
问题是我能够从数据库成功获取数据并能够在控制台中打印。。但是当我尝试通过GET请求通过浏览器访问它时,抛出404错误。。
我的pom.xml
<?xml version="1.0" encoding="UTF-8"?> <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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>hibernate.mapping.onetoone</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>hibernate.mapping.onetoone</name> <description>Demo project for Hibernate One to One</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.10.Final</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.15</version> </dependency> <!-- https://mvnrepository.com/artifact/jstl/jstl --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>5.2.2.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/c3p0/c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web-services</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> enter code here enter code here
和我的SpringMain应用程序类
package com.example.hibernate.crud; import java.beans.PropertyVetoException; import java.util.Properties; import javax.sql.DataSource; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.orm.hibernate5.HibernateTransactionManager; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import com.mchange.v2.c3p0.ComboPooledDataSource; @SpringBootApplication @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) @ComponentScan("com.example.hibernate.crud.*") @EntityScan("com.example.hibernate.crud.*") @EnableTransactionManagement @PropertySource({"classpath:persistence-mysql.properties"}) public class HibernateApplication implements WebMvcConfigurer { @Autowired private Environment env; public static void main(String[] args) { SpringApplication.run(HibernateApplication.class, args); } @Bean public DataSource myDataSource() { // create connection pool ComboPooledDataSource myDataSource = new ComboPooledDataSource(); // set the jdbc driver try { myDataSource.setDriverClass("com.mysql.cj.jdbc.Driver"); } catch (PropertyVetoException exc) { throw new RuntimeException(exc); } // set database connection props myDataSource.setJdbcUrl(env.getProperty("jdbc.url")); myDataSource.setUser(env.getProperty("jdbc.user")); myDataSource.setPassword(env.getProperty("jdbc.password")); // set connection pool props myDataSource.setInitialPoolSize(Integer.parseInt(env.getProperty("connection.pool.initialPoolSize"))); myDataSource.setMinPoolSize(Integer.parseInt(env.getProperty("connection.pool.minPoolSize"))); myDataSource.setMaxPoolSize(Integer.parseInt(env.getProperty("connection.pool.maxPoolSize"))); myDataSource.setMaxIdleTime(Integer.parseInt(env.getProperty("connection.pool.maxIdleTime"))); return myDataSource; } private Properties getHibernateProperties() { Properties props = new Properties(); props.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); props.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); return props; } @Bean public LocalSessionFactoryBean sessionFactory(){ // create session factorys LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); // set the properties sessionFactory.setDataSource(myDataSource()); sessionFactory.setPackagesToScan(env.getProperty("hibernate.packagesToScan")); sessionFactory.setHibernateProperties(getHibernateProperties()); return sessionFactory; } @Bean @Autowired public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) { // setup transaction manager based on session factory HibernateTransactionManager txManager = new HibernateTransactionManager(); txManager.setSessionFactory(sessionFactory); return txManager; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry .addResourceHandler("/resources/**") .addResourceLocations("WEB-INF/resources/"); } }
和我的控制器类
package com.example.hibernate.crud.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import com.example.hibernate.crud.DAO.CustomerDAO; import com.example.hibernate.crud.entity.Customer; @Controller @RequestMapping("/student") public class StudentController { @Autowired CustomerDAO customerDAO; @GetMapping("/list") public List<Customer> getStudentList() { return customerDAO.getAllCustomers(); } }
和我的实体类
package com.example.hibernate.crud.entity; 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="customer") public class Customer { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private int id; @Column(name="first_name") private String firstName; @Column(name="last_name") private String lastName; @Column(name="email") private String email; public Customer() { } public Customer(String firstName, String lastName, String email) { this.firstName = firstName; this.lastName = lastName; this.email = email; } @Override public String toString() { return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]"; } }
和我的DAO界面:
package com.example.hibernate.crud.DAO; import java.util.List; import com.example.hibernate.crud.entity.Customer; public interface CustomerDAO { public List<Customer> getAllCustomers(); }
我的DAO实现类:
package com.example.hibernate.crud.DAO; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.example.hibernate.crud.entity.Customer; @Repository public class CustomerDAOImpl implements CustomerDAO { @Autowired SessionFactory sessionfactory; @Override @Transactional public List<Customer> getAllCustomers() { Session session = sessionfactory.getCurrentSession(); System.out.println("REACHED UNTIL THIS..,"); Query<Customer> query = session.createQuery("from Customer", Customer.class); //session.getTransaction().commit(); for(Customer c : query.getResultList()) { System.out.println("REACHED LOOP"); System.out.println(c); } return query.getResultList(); } }
我的属性文件:
时,我将获得以下登录控制台:# # JDBC connection properties # jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC jdbc.user=root jdbc.password= # # Connection pool properties # connection.pool.initialPoolSize=5 connection.pool.minPoolSize=5 connection.pool.maxPoolSize=20 connection.pool.maxIdleTime=3000 # # Hibernate properties # hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show_sql=true hibernate.packagesToScan=com.example.hibernate.crud.entity
并且当我运行我的应用程序并在浏览器中点击以下URL “ http://localhost:8080/student/list”
正如您从日志中看到的那样,数据是从DB提取并打印在控制台中的。但是,当在浏览器中返回时,如下所示:404]]
无法理解为什么会发生。.请澄清。.
附加数据库模型以供参考:DB Model image
我目前正在使用Hibernate学习Spring。.我有一个简单的Customer表,其中的列是“ ID”,“ first_name”,“ last_name”,“ email”。我使用hibernate查询数据库并列出结果.. 。
查看此问题很可能是您的控制器。您已经用@Controller而不是@RestController注释了控制器。查看此article;
@ Controller的工作是创建模型对象的Map并查找一个视图,但是@RestController只是返回对象和对象数据直接以JSON或XML形式写入HTTP响应。