1

Я новичок и пытаюсь осваивать Spring. Хочу сделать выборку из таблицы products, с использованием Spring. Делал по статье http://learningprogramming.net/java/spring-mvc/read-data-from-database-with-spring-data-jpa-in-spring-mvc/. Программирую в среде NetBeans 8.2, использую встроенный сервер GlassFish Server, проект веб-приложение Java maven. Вот структура проекта: введите сюда описание изображения Вот структура таблицы products: введите сюда описание изображения

Код 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mycompany</groupId>
    <artifactId>testTask</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>testTask</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>



        <!-- JSTL tag lib -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>javax.servlet.jsp.jstl-api</artifactId>
            <version>1.2.1</version>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>


        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>2.0</version>
</dependency>

<dependency>
    <groupId>postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.1-901.jdbc4</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>2.0.7.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>2.0.5</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>3.0.5.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>2.0.5</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>2.5.4</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>3.0.2.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>2.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>3.0.2.RELEASE</version>
</dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>7.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Код application.properties:

# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.

spring.mvc.view.prefix = /WEB-INF/views/
spring.mvc.view.suffix = .jsp
spring.mvc.static-path-pattern=/resources/**

spring.datasource.url=jdbc:postgresql://localhost:5432/basefortesttask
spring.datasource.username=postgres
spring.datasource.password=admin1234
spring.jpa.generate-ddl=true

Код ProductController:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Data
 */
package com.demo.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.demo.services.ProductService;

@Controller
@RequestMapping("product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @RequestMapping(method = RequestMethod.GET)
    public String index(ModelMap modelMap) {
        modelMap.put("products", productService.findAll());
        return "product/index";



}
}

Код Product.java:

package com.demo.entities;

import java.math.BigDecimal;
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 = "product")
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column
    private String productname;

    @Column
    private int price;

    @Column
    private int productcount;

    @Column
    private String manufacturer;

    public int getPrice() {
        return price;
    }

    public String getProductname() {
        return productname;
    }

    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public void setProductname(String productname) {
        this.productname = productname;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setProductcount(int productcount) {
        this.productcount = productcount;
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public int getProductcount() {
        return productcount;
    }

    public int getId() {
        return id;
    }




}

Код ProductRepository:

package com.demo.repositories;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.demo.entities.Product;


    @Repository("productRepository")
public interface ProductRepository extends CrudRepository<Product, Integer> {
}

Код ProductService:

package com.demo.services;

import com.demo.entities.Product;

public interface ProductService {

public Iterable<Product> findAll();

}

Код ProductServiceImpl:

package com.demo.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.demo.entities.Product;
import com.demo.repositories.ProductRepository;
import com.demo.services.ProductService;

@Transactional
@Service("productService")

public class ProductServiceImpl {

    @Autowired
    private ProductRepository productRepository;

    public Iterable<Product> findAll() {
        return productRepository.findAll();
    }

}

Код index.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Products List</title>
</head>
<body>

    <h3>Products List</h3>
    <table border="1" cellpadding="2" cellspacing="2">
        <tr>
            <th>Id</th>
            <th>productname</th>
            <th>Description</th>
            <th>productcount</th>
            <th>productcount</th>
            <th>price</th>
        </tr>
        <c:forEach var="product" items="${products }">
            <tr>
                <td>${product.id }</td>
                <td>${product.productname }</td>
                <td>${product.manufacturer }</td>
                <td>${product.productcount }</td>
                <td>${product.price }</td>

            </tr>
        </c:forEach>
    </table>

</body>
</html>

Помогите пожалуйста разобраться с проблемой.

1 ответ 1

0

1) добавьте в application.properties spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true

2) как всё-таки называется таблица, product или products?

3) у вас в мавене версия 9.1 постгре, то есть несколько не новая. Какая версия postgresql установлена в системе?

8
  • таблица называется products версия postgresql установлена 10 16 ноя 2019 в 16:21
  • я добавил строки spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true но всё равно выводятся только заголовки столбцов таблицы 16 ноя 2019 в 16:27
  • в коде @Table(name = "product"), так что ещё раз перепроверьте, что название таблицы в базе и в коде совпадает 16 ноя 2019 в 16:27
  • изменил на @Table(name = "products") но всё равно ничего не выводит 16 ноя 2019 в 16:30
  • Свежая версия jdbc-драйвера живёт здесь mvnrepository.com/artifact/org.postgresql/postgresql/42.2.8 (у них сменился groupId). Попробуйте с ней. 16 ноя 2019 в 16:34

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.