Я изучаю javaEE. Прежде чем я разместил аннотацию OneToMany
и ManyToOne
, все работает хорошо. Но затем я вижу эту ошибку:org.hibernate.ObjectNotFoundException: не существует строки с данным идентификатором
INFO: HHH000327: Error performing load command : org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [app.web.landingpage.object.Category#28] getIndexPost org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [app.web.landingpage.object.Category#28]
Я не могу выбрать всю информацию о db или insert. Я использую шаблон DAO, Hibernate
Категория
@Entity
@Table(name="CATEGORY")
public class Category {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "ID", insertable=false, nullable=false)
private int id;
@Column(name="NAMECAT")
private String nameCat;
@Column(name="INDEX")
private boolean index;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
private Set<Posts> post;
//then get and set
сообщений
@Entity(name="Posts")
@Table(name="POSTS")
public class Posts implements java.io.Serializable{
private static final long serialVersionUID = 1L;
@Id @GeneratedValue
@Column(name = "ID", unique = true, nullable = false)
private int id;
@Column(name="NAMEPOST", nullable = false)
private String namePost;
@Column(name="TEXT", nullable = false)
private String text;
@Column(name="IDCAT", nullable = false, insertable=false, updatable=false)
private int idCat;
@ManyToOne(optional = false)
@JoinColumn(name = "ID", insertable=false, updatable=false)
private Category category;
//then get and set
интерфейсCategoryDao
public interface CategoryDao {
public Collection getAllCategory();
}
интерфейсPostDao
public interface PostDao {
public Collection getIndexPost();
}
CategoryDaoImpl
public Collection getAllCategory() {
Session session = null;
List categoris = new ArrayList<Category>();
try{
session = HibernateUtil.getSessionFactory().openSession();
categoris = session.createCriteria(Category.class).list();
}catch(Exception e) {
System.out.println("getAllCategory "+ e);
}finally{
if(session != null && session.isOpen())
session.close();
}
return categoris;
}
PostDaoImpl
public Collection getIndexPost() {
List<Posts> posts = null;
Session session = null;
try{
session = HibernateUtil.getSessionFactory().openSession();
SQLQuery q = (SQLQuery)
session.createSQLQuery("select p.* from posts p join category c on c.index=1");
q.addEntity(Posts.class);
posts = q.list();
} catch(Exception e) { outputError("getIndexPost", e);
} finally{ closeSession(session); }
return posts;
}
И это сервлет категории выходов и сообщений
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
try{
//get all category
Collection allcategory = Factory.getInstance().getCatDAO().getAllCategory();
//get all post
Collection allpost = Factory.getInstance().getPostDAO().getIndexPost();
request.setAttribute("allcategory", allcategory);
request.setAttribute("allpost", allpost);
request.getRequestDispatcher("/index.jsp").forward(request, response);
} catch(Exception e) {
System.out.println(e);
} finally{
if(session!=null && session.isOpen())
session.close();
}
UPD:
Теперь вывод информации в порядке, но я не могу добавить в сообщений колонки idCat , прежде чем я добавить сообщения, как это :
String[] catarrayid = request.getParameterValues("eachcat");//get cat what user use
String textpost = request.getParameter("textpost"); //text post
String namepost = request.getParameter("namepost"); //name post
if(!textpost.isEmpty() && !namepost.isEmpty() && catarrayid!=null) {
//open session
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Posts post = new Posts();
//this value take id category
int id = 0;
for(String s : catarrayid) {
id = Integer.parseInt(s);
}
//create post object
post.setnamePost(namepost);
post.setText(textpost);
//this i add in table post value idCat
post.setIdCat(id);
try{
//and i add
Factory.getInstance().getPostDAO().addPost(post);
response.sendRedirect("indexadmin");
}catch(Exception e) {
System.out.println(e);
}finally{
if(session!=null && session.isOpen())
session.close();
}
но теперь я изменить сообщения как этот
@Id @GeneratedValue
@Column(name = "ID", unique = true, nullable = false)
private int id;
@Column(name="NAMEPOST", nullable = false)
private String namePost;
@Column(name="TEXT", nullable = false)
private String text;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "IDCAT", insertable=false, updatable=false)
private Category category;
и я не знаю, как добавить в пост значение idCat. В таблице post (id, namePost, Text, idCat). Категория (id, nameCat) Я стараюсь, но не удался
Я понял!Спасибо U – asdascascaedfa
Пожалуйста, посмотрите topik, я обновляю – asdascascaedfa
Не обновляйте этот уже ответ, и уже принятый вопрос. Задайте другой, отдельный вопрос. –