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

当我输入链接时,我得到了下面的错误。我如何修复这个问题?

卞成荫
2023-03-14

这是我的密码

新闻.java

package vn.aptech.musicstore.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;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 *
 * @author Dung
 */
@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Table(name = "news")
public class News {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;
    @Column(name = "title")
    private String title;
    @Column(name = "description")
    private String description;
    @Column(name = "image")
    private String image;
    @Column(name = "[view]")
    private Integer view;
    @Column(name = "created_at")
    private String created_at;
}

NewsRepository.java

package vn.aptech.musicstore.repository;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import vn.aptech.musicstore.entity.News;

/**
 *
 * @author Dung
 */
public interface NewsRepository extends JpaRepository<News, Integer>{
    @Query("SELECT o FROM News o WHERE o.title LIKE CONCAT('%',:title,'%')")
    List<News> findByTitleCustom(@Param("title") String title);
    
    List<News> findTop12ByOrderByIdDesc();
}

新闻ervice.java

package vn.aptech.musicstore.service;

import java.util.List;
import java.util.Optional;
import vn.aptech.musicstore.entity.News;
import vn.aptech.musicstore.pagination.Paged;

/**
 *
 * @author Dung
 */
public interface NewsService {
    List<News> findAll();
    Optional<News> findById(int id);
    News save(News news);
    void deleteById(int id);
    List<News> findByTitleCustom(String title);
    List<News> findTop12ByOrderByIdDesc();
    Paged<News> getPage(int pageNumber, int size);
}

NewsServiceImpl.java

package vn.aptech.musicstore.service.impl;

import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import vn.aptech.musicstore.entity.News;
import vn.aptech.musicstore.pagination.Paged;
import vn.aptech.musicstore.pagination.Paging;
import vn.aptech.musicstore.repository.NewsRepository;
import vn.aptech.musicstore.service.NewsService;

/**
 *
 * @author Dung
 */
@Controller
public class NewsServiceImpl implements NewsService {

    @Autowired
    private NewsRepository repo;

    @Override
    public List<News> findAll() {
        return repo.findAll();
    }

    @Override
    public Optional<News> findById(int id) {
        return repo.findById(id);
    }

    @Override
    public News save(News news) {
        return repo.save(news);
    }

    @Override
    public void deleteById(int id) {
        repo.deleteById(id);
    }

    @Override
    public List<News> findByTitleCustom(String title) {
        return repo.findByTitleCustom(title);
    }

    @Override
    public List<News> findTop12ByOrderByIdDesc() {
        return repo.findTop12ByOrderByIdDesc();
    }

    @Override
    public Paged<News> getPage(int pageNumber, int size) {
        PageRequest request = PageRequest.of(pageNumber - 1, size, Sort.by(Sort.Direction.DESC,"id"));
        Page<News> postPage = repo.findAll(request);
        return new Paged<>(postPage, Paging.of(postPage.getTotalPages(), pageNumber, size));
    }

}

NewsController.java

package vn.aptech.musicstore.controller.admin;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import vn.aptech.musicstore.entity.News;
import vn.aptech.musicstore.service.NewsService;

/**
 *
 * @author Dung
 */
@Controller
@RequestMapping("/admin/news")
public class NewsController {

    @Value("${static.base.url}")
    private String base_url;

    @Autowired
    private NewsService service;

    @GetMapping
    public String index(Model model, @RequestParam(value = "pageNumber", required = false, defaultValue = "1") int pageNumber,
            @RequestParam(value = "size", required = false, defaultValue = "10") int size) {
        model.addAttribute("list", service.getPage(pageNumber, size));
        model.addAttribute("service", service);
        model.addAttribute("title", "null");
        return "admin/news/index";
    }

    @GetMapping("/create")
    public String create(Model model) {
        model.addAttribute("news", new News());
        model.addAttribute("action", "create");
        return "admin/news/create";
    }

    @PostMapping("/save")
    public String save(Model model, @ModelAttribute("news") News news, @RequestParam("file") MultipartFile file) throws IOException {
        if (!(file.isEmpty())) {
            news.setImage(file.getOriginalFilename());
            Files.copy(file.getInputStream(), Paths.get(base_url + "\\webdata\\news" + File.separator + file.getOriginalFilename()), StandardCopyOption.REPLACE_EXISTING);
            service.save(news);
        } else {
            news.setImage(service.findById(news.getId()).orElseThrow().getImage());
            service.save(news);
        }
        return "redirect:/admin/news";
    }

    @GetMapping("/update/{id}")
    public String update(Model model, @PathVariable("id") int id) {
        model.addAttribute("news", service.findById(id).orElseThrow());
        model.addAttribute("action", "update");
        return "admin/news/create";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") int id) {
        service.deleteById(id);
        return "redirect:/admin/news";
    }

    @GetMapping("/search")
    public String search(Model model, @RequestParam("title") String title, @RequestParam(value = "pageNumber", required = false, defaultValue = "1") int pageNumber,
            @RequestParam(value = "size", required = false, defaultValue = "1000") int size) {
        model.addAttribute("list", service.getPage(pageNumber, size));
        model.addAttribute("service", service);
        model.addAttribute("title", title);
        return "admin/news/index";
    }
}

新闻ApiController.java

package vn.aptech.musicstore.api;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import vn.aptech.musicstore.entity.News;
import vn.aptech.musicstore.service.NewsService;

/**
 *
 * @author Dung
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/news")
public class NewsApiController {

    @Value("${static.base.url}")
    private String base_url;

    @Autowired
    private NewsService service;

    @GetMapping
    public List<News> findAll() {
        return service.findAll();
    }

    @GetMapping("/{id}")
    public Optional<News> findById(@PathVariable int id) {
        return service.findById(id);
    }

    @PostMapping
    public String create(@RequestParam("title") String title,
            @RequestParam("create_at") String date,
            @RequestParam("des") String des,
            @RequestParam("file") MultipartFile file) throws IOException {
        News news = new News();
        news.setTitle(title);
        news.setDescription(des);
        news.setImage(file.getOriginalFilename());
//        String path_directory = "C:\\Users\\namng\\Documents\\NetBeansProjects\\musicstore\\src\\main\\resources\\static\\image";
//        String path_directory = new ClassPathResource("static/image").getFile().getAbsolutePath();
        Files.copy(file.getInputStream(), Paths.get(base_url + "\\news" + File.separator + file.getOriginalFilename()), StandardCopyOption.REPLACE_EXISTING);
        news.setView(0);
        news.setCreated_at(date);
        service.save(news);
        return "created";
    }

    @DeleteMapping("/{id}")
    public String delete(@PathVariable int id) {
        service.deleteById(id);
        return "deleted";
    }

    @PutMapping
    public String update(@RequestParam("id") int id,
            @RequestParam("create_at") String date,
            @RequestParam("title") String title,
            @RequestParam("des") String des,
            @RequestParam("file") MultipartFile file) throws IOException {
        if (!(file.isEmpty())) {
            News news = new News();
            news.setId(id);
            news.setTitle(title);
            news.setDescription(des);
            news.setImage(file.getOriginalFilename());
            news.setView(0);
            news.setCreated_at(date);
            service.save(news);
//            String path_directory = "C:\\Users\\namng\\Documents\\NetBeansProjects\\musicstore\\src\\main\\resources\\static\\image";
            //        String path_directory = new ClassPathResource("static/image").getFile().getAbsolutePath();
            Files.copy(file.getInputStream(), Paths.get(base_url + "\\news" + File.separator + file.getOriginalFilename()), StandardCopyOption.REPLACE_EXISTING);
        } else {
            News news2 = service.findById(id).orElseThrow();
            News news = new News();
            news.setId(id);
            news.setTitle(title);
            news.setDescription(des);
            news.setImage(news2.getImage());
            news.setView(0);
            news.setCreated_at(date);
            service.save(news);
        }
        return "updated";
    }
}

templates.admin.news.create

<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{admin/layout.html}">
    <body>
        <div layout:fragment="content" id="content-page" class="content-page">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="iq-card">
                            <div class="iq-card-header d-flex justify-content-between">
                                <div class="iq-header-title">
                                    <h4 th:if="${action=='create'}" class="card-title">Add New News</h4>
                                    <h4 th:if="${action=='update'}" class="card-title">Update News</h4>
                                </div>
                            </div>
                            <div class="iq-card-body">
                                <form th:action=${"/admin/news/save"} th:object="${artist}" method="post" enctype="multipart/form-data" class="needs-validation" novalidate>
                                    <input type="hidden"  th:field="${news.id}" />
                                    <div class="form-group">
                                        <label for="validationCustom01">Artist Name(<span style="color: red;">*</span>):</label>
                                        <input type="text" th:field="${news.title}" id="validationCustom01" class="form-control" required>
                                        <div class="valid-feedback">
                                            Looks good!
                                        </div>
                                        <div class="invalid-feedback">
                                            Required
                                        </div>
                                    </div>
                                    <div th:if="${action=='create'}" class="form-group">
                                        <label>Picture(<span style="color: red;">*</span>):</label>
                                        <div class="custom-file">
                                            <input type="file" name="file" class="custom-file-input" id="customFile" required>
                                            <label class="custom-file-label" for="customFile">Choose file</label>
                                            <div class="invalid-feedback">Required</div>
                                        </div>
                                    </div>
                                    <div th:if="${action=='update'}" class="form-group">
                                        <label>Picture(<span style="color: red;">*</span>):</label>
                                        <div class="custom-file">
                                            <input type="file" name="file" class="custom-file-input" id="customFile">
                                            <label class="custom-file-label" for="customFile">Choose file</label>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label>Description:</label>
                                        <textarea th:field="${news.description}" class="form-control" rows="8"></textarea>
                                    </div>               
                                    <button type="submit" class="btn btn-primary">Submit</button>
                                    <button type="reset" class="btn btn-danger">Reset</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

templates.admin.news.index

<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{admin/layout.html}">
    <body>
        <div layout:fragment="content" id="content-page" class="content-page">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="iq-card">
                            <div class="iq-card-header d-flex justify-content-between">
                                <div class="iq-header-title">
                                    <h4 class="card-title">News Lists</h4>
                                </div>
                                <div class="iq-search-bar">   
                                    <form th:action="@{/admin/news/search}" class="searchbox">
                                        <input type="text" class="text search-input" name="name" placeholder="Search Here..">
                                        <a class="search-link" href="#"><i class="ri-search-line text-black"></i></a>
                                        <a class="search-audio" href="#"><i class="las la-microphone text-black"></i></a> 
                                    </form>
                                </div>
                                <div class="iq-card-header-toolbar d-flex align-items-center">
                                    <a th:href="@{/admin/news/create}" class="btn btn-primary">Add New News</a>
                                </div>
                            </div>
                            <div class="iq-card-body">
                                <div class="table-responsive">
                                    <table class="data-tables table table-striped table-bordered" style="width:100%">
                                        <thead>
                                            <tr>
                                                <th style="width: 5%;">No</th>
                                                <th style="width: 20%;">Picture</th>
                                                <th style="width: 15%;">Name</th>
                                                <!--  <th style="width: 15%;">Artist</th>
                                                <!--<th style="width: 10%;">Price</th>
                                                <th style="width: 10%;">Artist</th>
                                                    <th style="width: 30%;">Audio</th> -->
                                                <th style="width: 10%;">Action</th> 
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr th:if="${name=='null'}" th:each="item:${list.page}">
                                                <td th:text="${service.findAll().size-service.findAll().indexOf(item)}"></td>
                                                <td>
                                                    <img style="width: 160px;height: 150px;" th:src="@{'/webdata/news/'+${item.image}}" class="img-fluid avatar-50 rounded" alt="author-profile">
                                                </td>
                                                <td th:text="${item.title}"></td>
                                                <td>
                                                    <div class="flex align-items-center list-user-action">
                                                        <a class="bg-primary" data-toggle="tooltip" data-placement="top" title="" data-original-title="Edit" th:href="@{/admin/news/update/{id}(id=${item.id})}"><i class="ri-pencil-line"></i></a>
                                                        <a class="bg-primary" data-toggle="tooltip" data-placement="top" title="" data-original-title="Delete" th:href="@{/admin/news/delete/{id}(id=${item.id})}"><i class="ri-delete-bin-line"></i></a>
                                                    </div>
                                                </td>
                                            </tr>
                                            <!-- search case -->
                                            <tr th:if="${name!='null' && item.name.toLowerCase().contains(name.toLowerCase())}" th:each="item:${list.page}">
                                                <td th:text="${service.findAll().size-service.findAll().indexOf(item)}"></td>
                                                <td>
                                                    <img style="width: 160px;height: 150px;" th:src="@{'/webdata/news/'+${item.image}}" class="img-fluid avatar-50 rounded" alt="author-profile">
                                                </td>
                                                <td th:text="${item.title}"></td>
                                                <td>
                                                    <div class="flex align-items-center list-user-action">
                                                        <a class="bg-primary" data-toggle="tooltip" data-placement="top" title="" data-original-title="Edit" th:href="@{/admin/news/update/{id}(id=${item.id})}"><i class="ri-pencil-line"></i></a>
                                                        <a class="bg-primary" data-toggle="tooltip" data-placement="top" title="" data-original-title="Delete" th:href="@{/admin/news/delete/{id}(id=${item.id})}"><i class="ri-delete-bin-line"></i></a>
                                                    </div>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>  
            <nav th:if="${name=='null'}" aria-label="Page navigation" class="paging">
                <ul class="pagination" th:if="${list.page.totalPages > 1}">
                    <li class="page-item" th:classappend="${!list.paging.isPrevEnabled()? 'disabled' : ''}">
                        <a class="page-link" th:href="@{'/admin/news/?pageNumber=' + ${list.paging.pageNumber - 1}}"
                           tabindex="-1">Previous</a>
                    </li>
                    <th:block th:each="item : ${list.paging.getItems()}">
                        <li class="page-item" th:classappend="${item.index == list.paging.pageNumber? 'active' : ''}"
                            th:if="${item.pageItemType.name() == 'PAGE'}">
                            <a class="page-link" th:href="@{'/admin/news/?pageNumber=' + ${item.index}}"
                               th:text="${item.index}"></a>
                        </li>
                        <li class="page-item disabled" th:if="${item.pageItemType.name() == 'DOTS'}">
                            <a class="page-link" href="#">...</a>
                        </li>
                    </th:block>
                    <li class="page-item" th:classappend="${!list.paging.isNextEnabled()? 'disabled' : ''}">
                        <a class="page-link" th:href="@{'/admin/news/?pageNumber=' + ${list.paging.pageNumber + 1}}">Next</a>
                    </li>
                </ul>
            </nav>
        </div>                         
    </body>
</html>

当我点击链接去templates.admin.news.index,出现这个错误:

2022-07-25 21:48:42.127 ERROR 8956 --- [nio-8080-exec-5] o.h.engine.jdbc.spi.SqlExceptionHelper   : Incorrect syntax near the keyword 'view'.
2022-07-25 21:48:42.130 ERROR 8956 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause

com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword 'view'.
    

我正在做毕业设计。我的团队有4个人,每个人做一部分。我正在努力,不知道如何解决这个错误。希望你们能帮我解决。

共有1个答案

胡国兴
2023-03-14

根据https://support.microsoft.com/en-us/office/sql-reserved-words-b899948b-0e1c-4b56-9622-a03f8f07cfc8#bmdaidxsqlt_z单词"VIEW"是SQL服务器中的保留字,这意味着您不得将其用于列名等。

将您的column_name从[view]更改为文件N中的[view]ews.java并注意其他SQL命令和交叉引用中的用法。

 类似资料: