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

huangapple go评论75阅读模式
英文:

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

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
	&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
	&lt;parent&gt;
		&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
		&lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
		&lt;version&gt;2.2.6.RELEASE&lt;/version&gt;
		&lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
	&lt;/parent&gt;
	&lt;groupId&gt;com.example&lt;/groupId&gt;
	&lt;artifactId&gt;hibernate.mapping.onetoone&lt;/artifactId&gt;
	&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
	&lt;packaging&gt;war&lt;/packaging&gt;
	&lt;name&gt;hibernate.mapping.onetoone&lt;/name&gt;
	&lt;description&gt;Demo project for Hibernate One to One&lt;/description&gt;

	&lt;properties&gt;
		&lt;java.version&gt;1.8&lt;/java.version&gt;
	&lt;/properties&gt;

	&lt;dependencies&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-starter-jdbc&lt;/artifactId&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
		    &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
		    &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;
		    &lt;version&gt;5.4.10.Final&lt;/version&gt;
		&lt;/dependency&gt;
		&lt;!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --&gt;
		&lt;dependency&gt;
		    &lt;groupId&gt;mysql&lt;/groupId&gt;
		    &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
		    &lt;version&gt;8.0.15&lt;/version&gt;
		&lt;/dependency&gt;
		&lt;!-- https://mvnrepository.com/artifact/jstl/jstl --&gt;
		&lt;dependency&gt;
		    &lt;groupId&gt;jstl&lt;/groupId&gt;
		    &lt;artifactId&gt;jstl&lt;/artifactId&gt;
		    &lt;version&gt;1.2&lt;/version&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
        &lt;groupId&gt;org.apache.tomcat.embed&lt;/groupId&gt;
        &lt;artifactId&gt;tomcat-embed-jasper&lt;/artifactId&gt;
        &lt;scope&gt;provided&lt;/scope&gt;
    	&lt;/dependency&gt;
		
		&lt;!-- https://mvnrepository.com/artifact/org.springframework/spring-orm --&gt;
	&lt;dependency&gt;
    &lt;groupId&gt;org.springframework&lt;/groupId&gt;
    &lt;artifactId&gt;spring-orm&lt;/artifactId&gt;
    &lt;version&gt;5.2.2.RELEASE&lt;/version&gt;
	&lt;/dependency&gt;
	
	&lt;!-- https://mvnrepository.com/artifact/c3p0/c3p0 --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;c3p0&lt;/groupId&gt;
    &lt;artifactId&gt;c3p0&lt;/artifactId&gt;
    &lt;version&gt;0.9.1.2&lt;/version&gt;
&lt;/dependency&gt;
		
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-starter-web-services&lt;/artifactId&gt;
		&lt;/dependency&gt;

		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-starter-tomcat&lt;/artifactId&gt;
			&lt;scope&gt;provided&lt;/scope&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
			&lt;scope&gt;test&lt;/scope&gt;
			&lt;exclusions&gt;
				&lt;exclusion&gt;
					&lt;groupId&gt;org.junit.vintage&lt;/groupId&gt;
					&lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;
				&lt;/exclusion&gt;
			&lt;/exclusions&gt;
		&lt;/dependency&gt;
	&lt;/dependencies&gt;

	&lt;build&gt;
		&lt;plugins&gt;
			&lt;plugin&gt;
				&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
				&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
			&lt;/plugin&gt;
		&lt;/plugins&gt;
	&lt;/build&gt;

&lt;/project&gt;
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(&quot;com.example.hibernate.crud.*&quot;)
@EntityScan(&quot;com.example.hibernate.crud.*&quot;)
@EnableTransactionManagement
@PropertySource({&quot;classpath:persistence-mysql.properties&quot;})
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(&quot;com.mysql.cj.jdbc.Driver&quot;);
		 }
		 catch (PropertyVetoException exc) {
			 throw new RuntimeException(exc);
		 }
		 
		 // set database connection props
			myDataSource.setJdbcUrl(env.getProperty(&quot;jdbc.url&quot;));
			myDataSource.setUser(env.getProperty(&quot;jdbc.user&quot;));
			myDataSource.setPassword(env.getProperty(&quot;jdbc.password&quot;));
		 // set connection pool props
			myDataSource.setInitialPoolSize(Integer.parseInt(env.getProperty(&quot;connection.pool.initialPoolSize&quot;)));
			myDataSource.setMinPoolSize(Integer.parseInt(env.getProperty(&quot;connection.pool.minPoolSize&quot;)));
			myDataSource.setMaxPoolSize(Integer.parseInt(env.getProperty(&quot;connection.pool.maxPoolSize&quot;)));
			myDataSource.setMaxIdleTime(Integer.parseInt(env.getProperty(&quot;connection.pool.maxIdleTime&quot;)));
		 return myDataSource;
	}
	
	private Properties getHibernateProperties() {
		 
		 Properties props = new Properties();
		 props.setProperty(&quot;hibernate.dialect&quot;, env.getProperty(&quot;hibernate.dialect&quot;));
		 props.setProperty(&quot;hibernate.show_sql&quot;, env.getProperty(&quot;hibernate.show_sql&quot;));
		 return props;
	} 

	@Bean
	public LocalSessionFactoryBean sessionFactory(){
	 // create session factorys
		 LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
		 // set the properties
		 sessionFactory.setDataSource(myDataSource());
		 sessionFactory.setPackagesToScan(env.getProperty(&quot;hibernate.packagesToScan&quot;));
		 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(&quot;/resources/**&quot;)
	 .addResourceLocations(&quot;WEB-INF/resources/&quot;);
	}

}

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(&quot;/student&quot;)
public class StudentController {
	
	@Autowired CustomerDAO customerDAO;
	
	@GetMapping(&quot;/list&quot;)
	public List&lt;Customer&gt; 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=&quot;customer&quot;)
public class Customer {
	
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name=&quot;id&quot;)
	private int id;
	
	@Column(name=&quot;first_name&quot;)
	private String firstName;
	
	@Column(name=&quot;last_name&quot;)
	private String lastName;
	
	@Column(name=&quot;email&quot;)
	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 &quot;Customer [id=&quot; + id + &quot;, firstName=&quot; + firstName + &quot;, lastName=&quot; + lastName + &quot;, email=&quot; + email + &quot;]&quot;;
	}
	
	

}

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&lt;Customer&gt; 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&lt;Customer&gt; getAllCustomers() {
		
		Session session = sessionfactory.getCurrentSession();
		
		
			System.out.println(&quot;REACHED UNTIL THIS..,&quot;);
			
			Query&lt;Customer&gt; query = session.createQuery(&quot;from Customer&quot;, Customer.class);
			
			//session.getTransaction().commit();
			
			for(Customer c : query.getResultList()) {
				System.out.println(&quot;REACHED LOOP&quot;);
				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&amp;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:

The 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

THE browser Output image

Couldnt understand why it happens.. Please clarify..

Attaching DB model for reference:
DB Model image

答案1

得分: 1

问题很可能出在您的控制器上。您已经使用了@Controller而不是@RestController来注解您的控制器。
查阅这篇文章

@Controller的作用是创建一个模型对象的映射并查找视图,但@RestController只是返回对象,对象数据会直接以JSON或XML的形式写入HTTP响应中。

因此,您可以选择以下两种方法之一:

  1. 在您的getStudentList方法上添加@ResponseBody注解;
  2. 使用@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:

  1. Add @ResponseBody annotation to your getStudentList method;
  2. Annotate controller class with @RestController

hope this helps.

huangapple
  • 本文由 发表于 2020年5月3日 19:53:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/61574001.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定