当前位置: 首页 > 知识库问答 >
问题:

spring Hibernate,GET Query,Hibernate Query形成成功,我可以从DB中获取数据,但当我从浏览器中击中它的抛出404

高英彦
2023-03-14

我现在正在用Hibernate学习spring。我有一个简单的Customer表,其中列是“id”、“first_name”、“last_name”、“email”。

我使用hibernate查询数据库,并将所有客户的结果作为输出。我已经使用了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模型以供参考:DB模型映像

共有1个答案

狄珂
2023-03-14

看着它,问题很可能是你的控制器。您已经用@controller而不是@restcontroller注释了您的控制器。研究这篇文章;

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

所以基本上你可以做以下两件事:1。向getStudentList方法添加@ResponseBody注释;2.用@RestController注释controller类

希望这有帮助。

 类似资料:
  • 我有一个特定的XPATH查询,我使用它从某个HTML元素获取高度,当我通过XPATH助手插件在Chrome中执行它时,它会完美地返回所需的值。 然而,当我在Robot框架中通过Get-Element-Attribute关键字使用相同的查询时 ...然后我得到了一个关于这个XPATH的InvalidSelectorException。 因此,机器人框架或Selenium删除了@符号及其后的所有内容。

  • 我编写了一个日期选择器,用户可以在其中使用bootstrap在输入字段中输入日期: 在此之后,我将它与表单的一些其他信息一起插入到我的集合中,并将用户路由到一个新页面。 在那里,我想为我的倒计时计时器获取closeDateDB的信息,并在endtime时重定向用户 有人能帮我如何得到插入的CloseDateDB作为我倒计时的字符串吗??我是新来的流星,我真的很感激你的帮助。

  • 问题内容: 我已经创建了一个简单的 应用程序(使用),带有联系表单,当用户单击“提交”时,我想生成并发送电子邮件。为此,我一直试图像这样使用: …但是我在导入过程中遇到了很多错误。 我是否在这里缺少某些东西,或者根本不是为在浏览器中使用而设计的?如果是这种情况,我应该考虑其他选择吗? 问题答案: node.js用于服务器端JavaScript,它允许您执行浏览器无法完成的许多工作。 除了mailt

  • 我可以用这个条件对象来wait/notify/notifyall和synchronized方法吗? 还是坚持带锁的组合更好? 此外:

  • 我有一个API,它返回的数据类型为_HttpClientResponse,因为我使用的是httpClient,我使用下面的 当我打印结果i/flatter(23708):字符串i/flatter(23708):{“结果”:[{“IPAddress”:“192.1.1.1”,“说明”:“Windows 2016 Server”},{“IPAddress”:“192.1.1.1”,“说明”:“Wind

  • 问题内容: 我的脚本中有一个/子句。是否可以从子句中获取确切的错误消息? 问题答案: 不,无论是否有例外,时间都是无。采用: