英文:
Spring Hibernate, GET Query, Hibernate Query is formed successfully and I'm able to get data from DB, But when i hit from Browser its throwing 404
问题
I am currently learning Spring with Hibernate.
I have a simple Customer table where columns are "ID", "first_name", "last_name", "email".
I use hibernate to query the database and list the result of all customers as output.
I have used Spring boot along with MVC for the same.
The problem is I am able to fetch data from DB successfully and able to print in console.
But when I try to access it through browser by a GET request, Its throwing a 404 ERROR.
My pom.xml
<... (pom.xml content) ...>
and My SpringMain Application Class
<... (SpringMain Application Class content) ...>
And My Controller class
<... (Controller class content) ...>
And my Entity Class
<... (Entity Class content) ...>
And My DAO Interface:
<... (DAO Interface content) ...>
My DAO Implementation class:
<... (DAO Implementation class content) ...>
My properties file:
<... (properties file content) ...>
And when I run My application and hit following URL "http://localhost:8080/student/list" in browser I get the following Log in console:
[Console output image]
As you can see from the logs the data is fetched from DB and printed in the console.
But when in the browser it is returning 404 as follows
[Browser output image]
Couldnt understand why it happens.. Please clarify..
Attaching DB model for reference:
[DB Model image]
Note: The code and images in the original text have not been included in this translation.
英文:
I am currently learning Spring with Hibernate..
I have a simple Customer table where columns are "ID", "first_name", "last_name", "email"..
I use hibernate to query the database and list the result of all customers as output..
I have used Spring boot along with MVC for the same..
The problem is I am able to fetch data from DB successfully and able to print in console.. But when I try to access it through browser by a GET request, Its throwing a 404 ERROR..
My 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
and My SpringMain Application Class
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/");
}
}
And My Controller class
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();
}
}
And my Entity Class
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 + "]";
}
}
And My DAO Interface:
package com.example.hibernate.crud.DAO;
import java.util.List;
import com.example.hibernate.crud.entity.Customer;
public interface CustomerDAO {
public List<Customer> getAllCustomers();
}
My DAO Implementation class:
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();
}
}
My properties file:
#
# 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
And when I run My application and hit following URL "http://localhost:8080/student/list" in browser I get the following Log in console:
As you can see from the logs the data is fetched from DB and printed in the console..
But when in the browser it is returning 404 as follows
Couldnt understand why it happens.. Please clarify..
Attaching DB model for reference:
DB Model image
答案1
得分: 1
问题很可能出在您的控制器上。您已经使用了@Controller
而不是@RestController
来注解您的控制器。
查阅这篇文章;
@Controller
的作用是创建一个模型对象的映射并查找视图,但@RestController
只是返回对象,对象数据会直接以JSON或XML的形式写入HTTP响应中。
因此,您可以选择以下两种方法之一:
- 在您的
getStudentList
方法上添加@ResponseBody
注解; - 使用
@RestController
注解对控制器类进行标注。
希望这能帮到您。
英文:
Looking at it the problem is most likely your controller. You have annotated your controller with @Controller instead of a @RestController.
Look into this article;
> The job of the @Controller is to create a Map of model object and find
> a view but the @RestController simply returns the object and object
> data is directly written into HTTP response as JSON or XML.
So basically you can do two of the following:
- Add @ResponseBody annotation to your getStudentList method;
- Annotate controller class with @RestController
hope this helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论