I am Hibernate newbie, and developing a servlet which gets its parameters from a URL, creates a Hibernate object, then stores it into a MySQL database.
I am sending 1000 URLs concurrently. When I look at the MySQL table, it adds only the last object to the database.
doGet method:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//HttpSession session = request.getSession(true);
//session.putValue("uid", count);
String id = request.getParameter("id");
String url = request.getParameter("url");
String lastVisitTime = request.getParameter("lastVisitTime");
String visitCount = request.getParameter("visitCount");
String title = request.getParameter("title");
String typedCount = request.getParameter("typedCount");
HistoryItem hi = new HistoryItem(id, url, lastVisitTime, visitCount, title, typedCount);
File f = new File("C:\\Users\\atılay\\Desktop\\apache-tomcat-7.0.30-windows-x64\\jspservlets\\UserModeling\\src\\hibernate.cfg.xml");
SessionFactory sessionFactory = new Configuration().configure(f).buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(hi);
session.getTransaction().commit();
session.flush();
session.close();
}
HistoryItem:
public class HistoryItem {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
@Basic(optional = false)
private int i;
private String id = "";
private String url = "";
private String lastVisitTime = "";
private String visitCount = "";
private String title = "";
private String typedCount = "";
}
What is the problem? I could not find any solution.
If you're creating an object/entity to be saved into the database, you shouldn't be setting it's ID.
Allocating the ID happens when the object is saved -- and this is Hibernate's responsibility. Having the ID already set, means HB considers the object has been saved already.
Really this is not a very good question, or coding style, or example.
'Sending 1000 URL concurrently'. What does that mean? You have 1000 browsers open at once, and send a request from all of them simultaneously? Talk sense.
Your SessionFactory should be kept in the webapp or servlet. This code is doing an entire Hibernate startup & initialization, for every page request.
File f = new File("C:\\Users\\atılay\\Desktop\\apache-tomcat-7.0.30-windows-x64\\jspservlets\\UserModeling\\src\\hibernate.cfg.xml");
SessionFactory sessionFactory = new Configuration().configure(f).buildSessionFactory();
Get rid of 'ID' as a parameter -- or else use it optionally, to load & edit records -- and do the Hibernate setup properly.
Then your project might work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.