При отправлении формы получаю такую ошибку, при этом если я жму кнопку назад и отправляю форму повторно, то запрос срабатывает и добавление происходит, такая ошибка появляется только при работе с одним из трех классов, остальные работают нормально. Работа ведётся в базой данных расположенной на Heroku.
org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:115)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:102)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:129)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:247)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.begin(LogicalConnectionManagedImpl.java:254)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.begin(JdbcResourceLocalTransactionCoordinatorImpl.java:203)
at org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:56)
at org.hibernate.internal.AbstractSharedSessionContract.beginTransaction(AbstractSharedSessionContract.java:397)
at com.dao.episode.EpisodeDAOImpl.addEpisode(EpisodeDAOImpl.java:51)
at com.dao.episode.EpisodeServiceImpl.addEpisode(EpisodeServiceImpl.java:16)
at com.bascon.HelloController.addEpisodeAction(HelloController.java:133)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:745)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1437)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 90 830 milliseconds ago. The last packet sent successfully to the server was 14 milliseconds ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:988)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3552)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3452)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3893)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2526)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2673)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)
at com.mysql.jdbc.ConnectionImpl.setAutoCommit(ConnectionImpl.java:4842)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.poll(PooledConnections.java:84)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:186)
at org.hibernate.internal.NonContextualJdbcConnectionAccess.obtainConnection(NonContextualJdbcConnectionAccess.java:35)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:99)
... 48 more
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:3004)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3462)
... 58 more
Hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="session">
<property name="hibernate.connection.charSet">utf8</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.useUnicode">true</property>
<property name="hibernate.enable_lazy_load_no_trans">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">ac8c4d10</property>
<property name="hibernate.connection.url">jdbc:mysql://us-cdbr-iron-east-03.cleardb.net/heroku_7975f769758d9fa?reconnect=true?UseUnicode=yes&characterEncoding=utf8</property>
<property name="hibernate.connection.username">bf529a773566a9</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hibernate.id.new_generator_mappings">false</property>
<mapping class="com.model.Comment"/>
<mapping class="com.model.Image"/>
<mapping class="com.model.Episode"/>
</session-factory>
</hibernate-configuration>
EpisodeDAOimpl.java (Ошибочная)
package com.dao.episode;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.model.Comment;
import com.model.Episode;
public class EpisodeDAOImpl implements EpisodesDAO {
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Episode.class).buildSessionFactory();
public List<Episode> getAllEpisodes(int page) {
int first = 0;
for (int i=1;i<page;i++) {
first = first + 10;
}
Session sess = sessionFactory.openSession();
Transaction tx = null;
List<Episode> eps = new ArrayList<Episode>();
try {
tx = sess.beginTransaction();
Query query = sess.createQuery("FROM Episode");
query.setFirstResult(first);
query.setMaxResults(10);
eps = query.getResultList();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
sess.close();
}
return eps;
}
public void addEpisode(Episode episode) {
Session sess = sessionFactory.openSession();
Transaction tx = null;
try {
tx = sess.beginTransaction();
sess.save(episode);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
sess.close();
}
}
public void deleteEpisode(int id) {
Session sess = sessionFactory.openSession();
Transaction tx = null;
try {
tx = sess.beginTransaction();
Episode com = sess.load(Episode.class, id);
if (null != com) {
sess.delete(com);
}
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
} finally {
sess.close();
}
}
public Episode getEpisode(int id) {
Episode eps = null;
Session sess = sessionFactory.openSession();
Transaction tx = null;
try {
tx = sess.beginTransaction();
eps = sess.load(Episode.class, id);
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
sess.close();
}
return eps;
}
public long getCount() {
Session sess = sessionFactory.openSession();
Transaction tx = null;
long i = 0;
try {
tx = sess.beginTransaction();
i = (Long) sess.createQuery("select count(*) from Episode").uniqueResult();
} catch (Exception e) {
e.printStackTrace();
} finally {
sess.close();
}
return i;
}
}
Episode.java (Модель)
package com.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
@Table(name = "episodes_table")
public class Episode {
@Id
@GeneratedValue
@Column(name = "episode_id")
private int id;
@Column(name = "episode_title")
@NotNull
@Size(min = 5, max = 30)
private String title;
@Column(name = "episode_link")
@NotNull
@Size(max = 100)
private String link;
@Column(name = "episode_desc")
@NotNull
@Size(min = 5, max = 300)
private String desc;
@Column(name = "upload_data")
private Date date;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Episode(String title, String link,String desc, Date date) {
this.title = title;
this.link = link;
this.desc = desc;
this.date = date;
}
public Episode() {
this.date = new Date();
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
HelloController.java (Контроллер)
package com.bascon;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Blob;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.jboss.logging.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.support.PagedListHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
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.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.dao.comment.CommentService;
import com.dao.comment.CommentServiceImpl;
import com.dao.episode.EpisodeServiceImpl;
import com.dao.image.ImageServiceImpl;
import com.model.Comment;
import com.model.Episode;
import com.model.Image;
import com.validation.EpisodeValidation;
@Controller
public class HelloController {
@Autowired
ServletContext context;
@Autowired
EpisodeValidation epsiodeValidator;
private static final Logger logger = Logger.getLogger(HelloController.class);
//Три сервиса для работы с базой данных
CommentServiceImpl commentService = new CommentServiceImpl();
EpisodeServiceImpl episodeService = new EpisodeServiceImpl();
ImageServiceImpl imageService = new ImageServiceImpl();
//Приветственная страница
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView Welcome(){
ModelAndView md = new ModelAndView("Hello");
String rick = "https://www.youtube.com/embed/AqT-MJnbePM";
String title = "Добро пожаловать на мой сайт о Madness Combat";
md.addObject("title", title);
md.addObject("rick",rick);
return md;
}
//Игра в Project Nexus
@RequestMapping(value = "/playNexus", method = RequestMethod.GET)
public ModelAndView PlayNexus(){
ModelAndView md = new ModelAndView("Nexus");
Comment come = new Comment();
String title = "Здесь вы можеть сыграть в Madness Project Nexus";
String link = "http://www.newgrounds.com/portal/view/592473";
md.addObject("title", title);
md.addObject("link",link);
return md;
}
//Форма с добавлением эпизодов
@RequestMapping(value = "/addEpisode", method = RequestMethod.GET)
public ModelAndView AddEpisode(){
ModelAndView md = new ModelAndView("AddEpisode");
String title = "Добавить новый эпизод";
String but = "Загрузить";
String titlePlac = "Напишите название файла здесь";
String linkPlac = "Ссылка должна содержать https://www.youtube.com/embed/";
String descPlac = "Введите описание здесь";
Episode episode = new Episode();
md.addObject("episode",episode);
md.addObject("title",title);
md.addObject("titlePlac", titlePlac);
md.addObject("linkPlac", linkPlac);
md.addObject("descPlac", descPlac);
md.addObject("butto",but);
return md;
}
//Метод POST, добавляющий эпизод
@RequestMapping(value = "/addEpisodeAction", method = RequestMethod.POST)
public String addEpisodeAction(@Validated @ModelAttribute("episode") Episode episode, BindingResult result ,ModelMap map) throws UnsupportedEncodingException{
map.addAttribute("title", episode.getTitle());
map.addAttribute("link",episode.getLink());
map.addAttribute("desc",episode.getDesc());
/*epsiodeValidator.validate(episode, result);
if(result.hasErrors()){
return "redirect:/addEpisode";
} else {}*/
String mel = new String(episode.getTitle().getBytes("ISO-8859-1"), "UTF-8");
String mec = new String(episode.getLink().getBytes("ISO-8859-1"), "UTF-8");
String mev = new String(episode.getDesc().getBytes("ISO-8859-1"), "UTF-8");
episode.setTitle(mel);
episode.setLink(mec);
episode.setDesc(mev);
episodeService.addEpisode(episode);
return "redirect:/getSeries/1";
}
//Список эпизодов
@RequestMapping(value = "/getSeries/{id}")
public ModelAndView GetSeries(@PathVariable int id){
ModelAndView md = new ModelAndView("AllEpisodes");
String title = "Вы можеть смотреть сериал Madness Combat здесь";
long count = episodeService.getCount();
long pages = count / 10 + 1;
List<Episode> eps = episodeService.listEpisode(id);
for (Episode ep : eps) {
System.out.println(ep.getTitle());
}
System.out.println("https://www.youtube.com/embed/DrtlTO5eD0U".length() );
md.addObject("pages",pages);
md.addObject("episodes",eps);
md.addObject("title",title);
return md;
}
//Просмотр эпизодов
@RequestMapping(path = "/watchEpisode/{id}")
public ModelAndView watchEpisode(@PathVariable int id){
ModelAndView md = new ModelAndView("WatchEpisode");
Episode eps = episodeService.getEpisode(id);
String title = eps.getTitle();
md.addObject("title",title);
md.addObject("episode",eps);
return md;
}
//Метод POST добавления комметариев
@RequestMapping(value = "/addComment", method = RequestMethod.POST)
public String addComment(@Validated @ModelAttribute("comment") Comment comment, BindingResult result, ModelMap model ) throws UnsupportedEncodingException{
model.addAttribute("author", comment.getAuthor());
model.addAttribute("content", comment.getContent());
String mel = new String(comment.getAuthor().getBytes("ISO-8859-1"), "UTF-8");
String mec = new String(comment.getContent().getBytes("ISO-8859-1"), "UTF-8");
comment.setAuthor(mel);
comment.setContent(mec);
commentService.addComment(comment);
return "redirect:/comments/1";
}
//Список комметариев
@RequestMapping(value = "/comments/{id}")
public ModelAndView Commentaries(@PathVariable int id){
ModelAndView md = new ModelAndView("Comments");
String title = "Оставьте отзыв";
String post = "Отправить";
long count = commentService.getCount();
long pages = count / 5 + 1;
List<Comment> coms = commentService.listComments(id);
Comment comment = new Comment();
md.addObject("comment", comment);
md.addObject("comments",coms);
md.addObject("title",title);
md.addObject("Post",post);
md.addObject("pages", pages);
return md;
}
//Доступ к галерее (В разработке)
@RequestMapping(value = "/galery/{id}")
public ModelAndView Gallery(@PathVariable int id){
ModelAndView md = new ModelAndView("Gallery");
Image image = new Image();
long count = commentService.getCount();
long pages = count / 20 + 1;
List<Image> images = new ArrayList<Image>();
images = imageService.getGallery(id);
String title2 = "Посмотрите галерею";
String butto = "Загрузить картинку";
md.addObject("butto", butto);
md.addObject("title2",title2);
md.addObject("image",image);
md.addObject("images",images);
md.addObject("pages",pages);
return md;
}
//Добавление изображений (В разработке)
@RequestMapping(value = "/addImage", method = RequestMethod.POST)
public String addImage(@Validated @ModelAttribute("image") Image image, ModelMap map, BindingResult result ) throws IOException{
map.addAttribute("title", image.getTitle());
map.addAttribute("file", image.getFile());
String mel = new String(image.getTitle().getBytes("ISO-8859-1"), "UTF-8");
image.setTitle(mel);
imageService.addImage(image);
return "redirect:/galery/1";
}
}
UPD: Соединение падает через определенный промежуток времени, примерно 5 минут
UPD2: Я ошибся, проблемы соединения есть со всеми таблицами.