package com.lgx8.gateway.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Date;
import java.util.List;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.transaction.annotation.Transactional;
import com.lgx8.common.dao.impl.BaseDao;
import com.lgx8.gateway.dao.IOrderDao;
import com.lgx8.gateway.entities.OrderProduct;
import com.lgx8.gateway.entities.Orders;
import com.lgx8.right.entities.User;
@SuppressWarnings("unchecked")
public class OrdersDao extends BaseDao implements IOrderDao {
public List<Orders> findOrders(String hql, Object[] values) {
return this.getHibernateTemplate().find(hql, values);
}
@Transactional
public void updateOrders(Orders order) {
this.getHibernateTemplate().update(order);
}
public Orders findOrders(Long id) {
return getHibernateTemplate().get(Orders.class, id);
}
@Transactional
public void createOrders(Orders order) {
// order.setId(System.currentTimeMillis());
getHibernateTemplate().persist(order);
}
@Transactional
public Orders findCartByUserId(User user) {
String hql = "from Orders o where o.status="+Orders.STATUS_CART+" and o.user.id="+user.getId();
List<Orders> list = getHibernateTemplate().find(hql);
if(list==null||list.size()==0) {
Orders o = new Orders();
//o.setId(System.currentTimeMillis());
o.setUser(user);
o.setStatus(Orders.STATUS_CART);
o.setShoppingtime(new Date());
createOrders(o);
return o;
} else {
return list.get(0);
}
}
@Transactional
public void createOrderProduct(OrderProduct op) {
getHibernateTemplate().persist(op.getOrders());
getHibernateTemplate().persist(op);
}
@Transactional
public void deleteOrderProduct(long id) {
OrderProduct op = findOrderProduct(id);
if(op!=null) {
op.getOrders().getOrderProducts().remove(op);
getHibernateTemplate().delete(op);
}
}
public OrderProduct findOrderProduct(long id) {
return getHibernateTemplate().get(OrderProduct.class, id);
}
@Transactional
public void updateOrderProduct(OrderProduct op) {
getHibernateTemplate().update(op);
}
public void deleteOrdersByCondition(String[] ids) {
String sql = "delete from orders where id in (";
StringBuffer condition = new StringBuffer();
if (ids.length != 0) {
for (int i = 0; i < ids.length; i++) {
if (i < ids.length - 1) {
condition.append(ids[i] + ",");
} else {
condition.append(ids[i] + ")");
}
}
sql = sql + condition.toString();
Connection conn = null;
PreparedStatement ps = null;
try {
conn = SessionFactoryUtils.getDataSource(
getHibernateTemplate().getSessionFactory())
.getConnection();
ps = conn.prepareStatement(sql);
ps.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ps != null) {
try {
ps.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
}
}