I can't set deptID value which is a foreign key I tried many ways, but it doesn't work.
I am getting the values from HTML form.
mapping table units
public BigDecimal getUnitId() {
return this.unitId;
}
public void setUnitId(BigDecimal unitId) {
this.unitId = unitId;
}
public Depts getDepts() { //deptID column - FK
return this.depts;
}
public void setDepts(Depts depts) {
this.depts = depts;
}
my code
<%
SessionFactory sf= new Configuration().configure().buildSessionFactory();
Session s= sf.openSession();
Transaction t= s.beginTransaction();
String unitID= request.getParameter("unitID");
String deptID= request.getParameter("deptID");
String unitName= request.getParameter("unitName");
Units r= new Units(); //this code to set deptID
Depts y= new Depts();
r.setUnitId(new BigDecimal(unitID));
//r.setDepts(y.setDeptId(new BigDecimal(deptID)));//here is my problem
y.setDeptId(new BigDecimal(deptID));
r.setUnitName(unitName);
s.save(r);
t.commit();
out.println("done enserting");
%>
I could suspect the error by looking at your code that you're trying to save the value which you're receiving from your html page, instead of saving the object of your Department (or your class name which has deptID primary-key) class.
In order to save the deptID along with your record :-
you need to get the object of that class first. Something like this :-
Units r = new Units();
YourDepartmentClass d = getDeparmentRecord(id) //get the `YourDepartmentClass` class object on the basis of the id you're receiving
r.setDepId(d); //set/associate YourDepartmentClass object in your Unit's object
//save the record
Related
According to the logic of the application, I have a controller to remove the recycle bin. By the link we get the session id, by it we search for the user in the database and delete all the invoices associated with it.
#RequestMapping(path="/basket/del/{sessId}", method=RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public BasketListReply delAllProducts(#PathVariable String sessId){
BasketListReply rep = new BasketListReply();
try {
//check if session exist
List<Long> delList = userService.findInvoiceBySessionId(sessId);
//delList contain list of invoices id to delete
if(delList != null) {
for(int i=0;i<delList.size();i++){
invoiceService.delInvoice(delList.get(i));
}
}
}catch(Exception e){
rep.retcode = -1;
rep.error_message = e.getMessage();
}
return rep;
}
With method findInvoiceBySessionId() I get list of invoices from collection () to delete.
public List findInvoiceBySessionId(String sessId) throws Exception{
List list = new ArrayList();
List<Appuser> users = findUserBySessionId(sessId);
if(!users.isEmpty()) {
//if exist, then extract invoices for this user
Appuser u = users.get(0);
List<Invoice> invoices = (List<Invoice>)u.getInvoiceCollection();
for(Invoice inv:invoices) {
list.add(inv.getOrderId());
}
}
return list;
}
Method delInvoice() I use to delete invoice from repository.
public void delInvoice(Long orderId){
if(invoiceRepository.findOne(orderId) == null) {
return;
}
invoiceRepository.delete(orderId);
}
File Appuser.java (field that contain collection of Invoices):
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private Collection<Invoice> invoiceCollection;
Did I understand correctly that I can not in one controller and extract data from the database via JPA and delete the same data ... since the deletion should go in a separate transaction.
Or am I doing something wrong?
When I delete the data by redirecting the request to the controller to delete the data, everything works fine.
I am currently working on a web application which is basically a portfolio site for different vendors.
I was working on a thread which copies the details of a vendor and puts it against a new vendor, pretty straightforward.
The thread is intended to work fine but when selecting a particular Catalog object (this catalog object contains a Velocity template), the execution stops and it goes nowhere. Invoking the thread once again just hangs the whole application.
Here is my code.
public class CopySiteThread extends Thread {
public CopySiteThread(ComponentDTO componentDTO, long vendorid, int admin_id) {
/**Application specific business logic not exposed **/
}
public void run() {
/** Application based Business Logic Not Exposed **/
//Copy Catalog first
List<Catalog> catalog = catalogDAO.getCatalog(vendorid);
System.out.println(catalog);
List<Catalog> newCat = new ArrayList<Catalog>();
HashMap<String, Integer> catIdMapList = new HashMap<String, Integer>();
Iterator<Catalog> catIterator = catalog.iterator();
while (catIterator.hasNext()) {
Catalog cat = catIterator.next();
System.out.println(cat);
int catId = catalogDAO.addTemplate(admin_id, cat.getHtml(), cat.getName(), cat.getNickname(), cat.getTemplategroup(), vendor.getVendorid());
catIdMapList.put(cat.getName(), catId);
cat = null;
}
}
}
And the thread is invoked like this.
CopySiteThread thread = new CopySiteThread(componentDTO, baseVendor, admin_id);
thread.start();
After a certain number of iterations, it gets stuck on line Catalog cat = catIterator.next();
This issue is rather strange because I've developed many applications like this without any problem.
Any help appreciated.
The actual problem was in the addCatalog method in CatalogDAO
Session session = sf.openSession();
Transaction tx = null;
Integer templateID = null;
Date date = new Date();
try {
tx = session.beginTransaction();
Catalog catalog = new Catalog();
//Business Logic
templateID = (Integer) session.save(catalog);
} catch (HibernateException ex) {
if (tx != null) tx.rolback();
} finally {
session.close();
}
return templateID;
Fixed by adding a finally clause and closing all sessions.
I've a question on hibernate operation: update.
Here a bit of code:
Campaign campaign = campaignDAO.get(id);
campaign.setStatus(true);
campaignDAO.update(campaign);
If I just have all the data of the campaign object, is there any way to perform an update without perform the first select (campaignDAO.get(id)) ?
Thanks,
Alessio
HQL will definitely help you.
In order to maintain the separation of concerns, you can add a more specialized method in you DAO object:
public void updateStatusForId(long id, boolean status){
//provided you obtain a reference to your session object
session.createQuery("UPDATE Campaign SET status = " + status + " WHERE id = :id").setParameter("id", id).executeUpdate();
//flush your session
}
Then you could simply call this method from your business method. You can check the generated SQL statements inside the logs of your app by setting the show_sql hibernate property to true.
You can use session.load(). It will not hit the database. Here you can find its details and example code.
I had worte a extension to solve this issue in Nhibernate
how to use!
first of all you need enable dynamic-update="true"
using (ISession session = sessionFactory.OpenSession())
{
Customer c1 = new Customer();
c1.CustomerID = c.CustomerID;
session.Mark(c1);
// c1.Name = DateTime.Now.ToString();
c1.Phone = DateTime.Now.ToString();
//需要开启动态更新
session.UpdateDirty(c1);
session.Flush();
}
UpdateExtension.cs
public static class UpdateExtension
{
static readonly Object NOTNULL = new Object();
public static void UpdateDirty<TEntity>(this ISession session, TEntity entity)
{
SessionImpl implementor = session as SessionImpl;
EntityEntry entry = implementor.PersistenceContext.GetEntry(entity);
if (entry == null)
{
throw new InvalidOperationException("找不到对应的实例,请先使用Mask方法标记");
}
IEntityPersister persister = entry.Persister;
// 如果某列不可以为空,新的Entity里也不想更新他。
// 那么LoadState 里的值应该和Entity 中的值相同
Object[] CurrentState = entry.Persister.GetPropertyValues(entity, EntityMode.Poco);
Object[] LoadedState = entry.LoadedState;
int[] dirtys = persister.FindDirty(CurrentState
, LoadedState
, entity
, (SessionImpl)session);
if (dirtys == null || dirtys.Length == 0)
{
return;
}
persister.Update(entry.Id
, CurrentState
, dirtys
, true
, LoadedState
, entry.Version
, entity
, entry.RowId
, (SessionImpl)session);
implementor.PersistenceContext.RemoveEntry(entity);
implementor.PersistenceContext.RemoveEntity(entry.EntityKey);
session.Lock(entity, LockMode.None);
// 防止(implementor.PersistenceContext.EntityEntries.Count == 0)
}
public static void Mark<TEntity>(this ISession session, TEntity entity)
{
session.Lock(entity, LockMode.None);
}
}
here is update sql
command 0:UPDATE Customers SET Phone = #p0 WHERE CustomerID = #p1;#p0 = '2014/12/26 0:12:56' [Type: String (4000)], #p1 = 1 [Type: Int32 (0)]
Only update Phone column .
event Name property can not be null. we can work very well.
I have a function that add into my database (using JPA) a user and his items ,the relationship many-to- many. I have the following tables :
profilUser
item
associationProfileUserItem
on the GUI I enter the login and password of the user and I choose a list of names of items, I have worte a function recuperate id of Item BY their name (to add them to the association).
the problem is that the function insert just the last item choosen for the user and ignore the rest!
My code:
public void addProfilUser()
{
try{
EntityTransaction entr=em.getTransaction();
entr.begin();
AssociationItemProfilPK ItemprofilPk=new AssociationItemProfilPK();
AssociationItemProfil Itemprofil=new AssociationItemProfil();
ProfilUser user=new ProfilUser();
user.setLogin(login);
user.setPassword(password);
em.persist(user);
for (Integer val : getListidItemByItemName())
{
ItemprofilPk.setItemId(val);
ItemprofilPk.setProfilId(user.getProfilUserId());
Itemprofil.setAssociationItemProfilPK(ItemprofilPk);
}
em.persist(Itemprofil);
entr.commit();
}
catch (Exception e )
{
System.out.println(e.getMessage());
System.out.println("Failed");
}
finally {
em.close();
emf.close();
}
}
public ArrayList<Integer> getListidItemByItemName()
{
try{
EntityTransaction entityTrans=emm.getTransaction();
entityTrans.begin();
for (String val : listItem)
{
System.out.println("my values"+val);
javax.persistence.Query multipleSelect= em.createQuery("SELECT i.ItemId FROM Item i WHERE i.ItemName IN (:w)" );
multipleSelect.setParameter("w", val);
List ItemId = new LinkedList();
ItemId= multipleSelect.getResultList();
listIdItem = new ArrayList(ItemId);
}
entityTrans.commit();
System.out.println("Id for given item name"+listIdItem);
return listIdItem;
}
catch(Exception e)
{
e.printStackTrace();
}
There are several problems with your code.
First one: you don't respect naming conventions. variables should start with a lower-case letter. This makes your code harder to read for seasoned Java programmers.
Second one: you loop over your item IDs, and change the value of your ItemprofilPk and Itemprofil objects. But you update always the same objects, and only persist the item after the loop. so, of course, only the last value is persisted. Change to something like this:
for (Integer val : getListidItemByItemName()) {
AssociationItemProfilPK itemprofilPk = new AssociationItemProfilPK();
AssociationItemProfil itemprofil = new AssociationItemProfil();
itemprofilPk.setItemId(val);
itemprofilPk.setProfilId(user.getProfilUserId());
itemprofil.setAssociationItemProfilPK(itemprofilPk);
em.persist(itemprofil);
}
Third one: your mapping is more complex than id needs. You should not have an entity to map the association table. Instead, you should thus have a list of items in the ProfilUser entity, and a list of profilUsers in the Item entity :
public class ProfilUser {
#ManyToMany
#JoinTable(
name = "associationProfileUserItem",
joinColumns = #JoinColumn(name = "PROFIL_ID"),
inverseJoinColumns=#JoinColumn(name="ITEM_ID")
private List<Item> items;
}
public class Item {
#ManyToMany(mappedBy = "items")
private List<ProfilUser profilUsers;
}
I want to insert data into a table using the following code
public User registerUser(String usr, String pwd) {
u=em.find(User.class,usr);
if(u!=null)
{
return null;
}
String query1 = "insert into users values('" + usr + "','" + pwd +"')";
Query q = em.createQuery(query1);
u=em.find(User.class,usr);
return u;
}
here 'u' is the object of User class and em is EntityManager.
I get this following exception:
Servlet.service() for servlet action threw exception
org.hibernate.hql.ast.QuerySyntaxException: expecting OPEN, found 'values' near line 1, column 19 [insert into users values('pawan','am')]
Try
public User registerUser(String usr, String pwd) {
u=em.find(User.class,usr);
if(u!=null)
{
return null;
}
//Now saving...
em.getTransaction().begin();
em.persist(u); //em.merge(u); for updates
em.getTransaction().commit();
em.close();
return u;
}
If the PK is Identity, it will be set automatically in your persisted class, if you are using auto generation strategy (thanks to David Victor).
Edit to #aman_novice comment:
set it in your class
//Do this BEFORE getTransaction/persist/commit
//Set names are just a example, change it to your class setters
u.setUsr(usr);
u.setPwd(pwd);
//Now you can persist or merge it, as i said in the first example
em.getTransaction().begin();
(...)
About #David Victor, sorry I forgot about that.
You're not using SQL but JPAQL, there is no field-based insert. You persist object rather than inserting rows.
You should do something like this:
public User registerUser(String usr, String pwd) {
u=em.find(User.class,usr);
if(u!=null)
{
return u;
}
u = new User(usr, pwd);
em.persist(u);
return u;
}
This isn't really the way to go. You are trying to insert a row in a table but have no associated attached entity. If you're using the JPA entity manager - then create a new instance - set the properties & persist the entity.
E.g.
User u = new User();
u.setXXX(xx);
em.persist(u);
// em.flush() <<-- Not required, useful for seeing what is happening
// etc..
If you enable SQL loggging in Hibernate & flush the entity then you'll see what is sent to the database.
E.g. in persistence.xml:
<property name="hibernate.format_sql" value="true" />