日期:2014-05-20  浏览次数:20696 次

hibernate为什么不能插入所以记录呢????
这是我写代码:

public void selectId(String[] id) {
Session select = HibernateSessionFactory.getSession();
Session insert = HibernateSessionFactory.getSession();
insert.createQuery("from Shoppingcart");
Transaction t=insert.beginTransaction();
Shoppingcart sc=new Shoppingcart();
Subgoods sg=new Subgoods();

for(int i=0;i<id.length;i++){
Query q=select.createQuery("from Subgoods where id="+Integer.valueOf(id[i]));
List l=q.list();
Iterator it=l.iterator();
while(it.hasNext()){
sg=(Subgoods)it.next();
sc.setName(sg.getName());
sc.setPrice(sg.getPrice());
insert.save(sc);
}
}
t.commit();
HibernateSessionFactory.closeSession();
}


public static void main(String[] args) {
ConnectionDB con=new ConnectionDB();
String id[]={"1","4"};
con.selectId(id);
}


怎么的问题就是:把Subgoods表的的id=4记录,插入到了Shoppingcart表中,可是id=1的记录为什么没有插入到Shoppingcart表中呢.

我传id值是1和4呀..

为什么只插入id=4呢...

还有就是我把insert.save(sc);换成insert.merge(sc);就可以把id=1和4的记录全部插入...

请高说帮帮忙????

------解决方案--------------------
for(int i=0;i <id.length;i++){ 
Transaction t=insert.beginTransaction(); 
Query q=select.createQuery("from Subgoods where id="+Integer.valueOf(id[i])); 
List l=q.list(); 
Iterator it=l.iterator(); 
while(it.hasNext()){ 
sg=(Subgoods)it.next(); 
sc.setName(sg.getName()); 
sc.setPrice(sg.getPrice()); 
insert.save(sc); 

t.commit(); 


HibernateSessionFactory.closeSession(); 



just do it
------解决方案--------------------
public void selectId(String[] id) { 
//Session select = HibernateSessionFactory.getSession(); 
Session insert = HibernateSessionFactory.getSession(); 
//insert.createQuery("from Shoppingcart"); 
Transaction t=insert.beginTransaction(); 
 
//Subgoods sg=new Subgoods(); 

for(int i=0;i <id.length;i++){ 
Query q=select.createQuery("from Subgoods where id="+Integer.valueOf(id[i])); 
List l=q.list(); 
Iterator it=l.iterator(); 
while(it.hasNext()){ 
Subgoods sg=(Subgoods)it.next(); 
Shoppingcart sc=new Shoppingcart();
sc.setName(sg.getName()); 
sc.setPrice(sg.getPrice()); 
insert.save(sc); 


t.commit(); 
HibernateSessionFactory.closeSession(); 



public static void main(String[] args) { 
ConnectionDB con=new ConnectionDB(); 
String id[]={"1","4"}; 
con.selectId(id);