Есть большая проблема... Не могу запустить и правильно структурировать проект. Что только не пробовал делать... Суть в чём: Впервые решил опробовать Hibernate + Spring. Вроде как всё настроил, база с хибернейтом работает отлично - но запустить и проверить что будет в конечном итоге в html так и не получилось.
По порядку:
Структура проекта:
Java
-->controller
---->MainController.java
-->dao
---->MessageDAO.java
-->model
---->Message.java
--Services
---->MessageServices.java
-->utils
---->HibernateUtil.java
-->Application.java
resources
-->templates
---->_menu.html
---->messagePage.html
-->hibernate.cfg.xml
<--pom.xml
MainController:
package controller;
import dao.MessageDAO;
import model.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
@Controller
public class MainController {
@Autowired
private MessageDAO messageDAO;
MainController(){}
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showMessage(Model model) {
List<Message> list = messageDAO.findAll();
model.addAttribute("Messages", list);
return "messagePage";
}
}
MessageDAO:
package dao;
import model.Message;
import org.hibernate.Session;
import org.hibernate.Transaction;
import utils.HibernateUtil;
import java.util.List;
public class MessageDAO {
public Message findById(int id){
return
HibernateUtil.getSessionFactory().openSession().get(Message.class, id);
}
public Message findByMessage(String message){
return
HibernateUtil.getSessionFactory().openSession().get(Message.class, message);
}
public void save(Message message){
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx1 = session.beginTransaction();
session.save(message);
tx1.commit();
session.close();
}
public void update(Message message){
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx1 = session.beginTransaction();
session.update(message);
tx1.commit();
session.close();
}
public void delete(Message message){
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx1 = session.beginTransaction();
session.delete(message);
tx1.commit();
session.close();
}
public List<Message> findAll() {
List<Message> messages = (List<Message>)
HibernateUtil.getSessionFactory().openSession().createQuery("From
Message").list();
return messages;
}
}
Message:
package model;
import javax.persistence.*;
@Entity
@Table (name = "Messages")
public class Message {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column
private String Message;
public Message(){}
public Message(String Message){
this.Message = Message;
}
public String getMessage() {
return Message;
}
public void setMessage(String message) {
Message = message;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
MessageService
package Services;
import dao.MessageDAO;
import model.Message;
import java.util.List;
public class MessageService {
private MessageDAO messageDAO = new MessageDAO();
public MessageService(){}
Message findMessage(int id) {
return messageDAO.findById(id);
}
Message findMessage(String message){
return messageDAO.findByMessage(message);
}
public void save(Message message){
messageDAO.save(message);
}
public void delete(Message message){
messageDAO.delete(message);
}
public void update(Message message){
messageDAO.update(message);
}
public List<Message> findAllMessage(){
return messageDAO.findAll();
}
}
HibernateUtil
package utils;
import model.Message;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private HibernateUtil(){}
public static SessionFactory getSessionFactory(){
if (sessionFactory == null) {
try{
Configuration configuration = new Configuration().configure();
configuration.addAnnotatedClass(Message.class);
StandardServiceRegistryBuilder builder = new
StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
sessionFactory =
configuration.buildSessionFactory(builder.build());
}catch (Exception e) {
System.out.println("Exception!!! " + e);
}
}
return sessionFactory;
}
}
Application
import controller.MainController;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(MainController.class, args);
}
}
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>DevYuriyIva</groupId>
<artifactId>MessagesControl</artifactId>
<version>1.0</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>7</source>
<target>7</target>
</configuration>
</plugin>
</plugins>
</build>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.6.Final</version>
</dependency>
<!-- dependencies for fixing bug when program is compiled -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>7.0.55</version>
</dependency>
</dependencies>
</project>
И тут уже хотел проверить, правильно ли поставил разметку в html, но Spring не запустился. messagePage.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Bank</title>
<style>
th, td {
padding: 5px;
}
</style>
</head>
<body>
<h2>MESSAGES</h2>
<table border="1">
<tr>
<th>ID</th>
<th>MESSAGE</th>
</tr>
<tr th:each="message : ${Messages}">
<td th:utext="${message.id}">..</td>
<td th:utext="${message.message}">..</td>
</tr>
</table>
</body>
</html>
Выдает примерно следующее:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.5.RELEASE)
2018-10-22 18:45:45.170 INFO 14728 --- [ main] Application
: Starting Application on Jeffrys with PID 14728
(D:\JAVA\MessagesControl\target\classes started by Jeffrys in
D:\JAVA\MessagesControl)
2018-10-22 18:45:45.170 INFO 14728 --- [ main] Application
: No active profile set, falling back to default profiles: default
2018-10-22 18:45:45.239 INFO 14728 --- [ main]
ConfigServletWebServerApplicationContext : Refreshing
org.springframework.boot.web.servlet.context.
AnnotationConfigServletWebServerApplicationContext@1be2019a: startup date
[Mon Oct 22 18:45:45 MSK 2018]; root of context hierarchy
2018-10-22 18:45:45.423 WARN 14728 --- [ main]
ConfigServletWebServerApplicationContext : Exception encountered during
context initialization - cancelling refresh attempt:
org.springframework.context.ApplicationContextException: Unable to start web
server; nested exception is
org.springframework.context.ApplicationContextException: Unable to start
ServletWebServerApplicationContext due to missing ServletWebServerFactory
bean.
2018-10-22 18:45:45.971 ERROR 14728 --- [ main]
o.s.boot.SpringApplication : Application run failed
org.springframework.context.ApplicationContextException: Unable to start web
server; nested exception is
org.springframework.context.ApplicationContextException: Unable to start
ServletWebServerApplicationContext due to missing ServletWebServerFactory
bean.
at org.springframework.boot.web.servlet.context.
ServletWebServerApplicationContext.onRefresh
(ServletWebServerApplicationContext.java:155) ~[spring-boot-
2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.context.support.
AbstractApplicationContext.refresh(AbstractApplicationContext.java:544) ~
[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at
org.springframework.boot.web.servlet.context.
ServletWebServerApplicationContext
.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-
2.0.5.RELEASE.jar:2.0.5.RELEASE]
at
org.springframework.boot.SpringApplication
.refresh(SpringApplication.java:780) [spring-boot-
2.0.5.RELEASE.jar:2.0.5.RELEASE]
... 8 common frames omitted
Process finished with exit code 1
Проект делаю по разным гайдам, тем самым учась и запоминая что за что отвечает. Но сейчас стал в тупик и не могу доделать вывод... help plz.
s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@59402b8f: startup date [Tue Oct 23 15:51:18 MSK 2018]; root of context hierarchy
иo.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
@VladMamaev