Example usage for org.apache.ibatis.session SqlSession insert

List of usage examples for org.apache.ibatis.session SqlSession insert

Introduction

In this page you can find the example usage for org.apache.ibatis.session SqlSession insert.

Prototype

int insert(String statement, Object parameter);

Source Link

Document

Execute an insert statement with the given parameter object.

Usage

From source file:action.postAsDriver.java

public String post() throws IOException {

    //connect database
    String resource = "orm/configuration.xml";
    Reader reader = Resources.getResourceAsReader(resource);
    SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
    SqlSession session = sessionFactory.openSession();

    try {//  ww  w.  jav a 2s . co m
        email = (String) (ActionContext.getContext().getSession().get("email"));
        numberofappliedpassengers = "0";
        System.out.println("email in pad=" + email);
        System.out.println("departure in pad=" + departure);
        System.out.println("destination in pad=" + destination);
        System.out.println("ddate in pad=" + departuredate);
        System.out.println("time in pad=" + estimatedleavingtime);
        System.out.println("seats in pad=" + availableseats);
        System.out.println("car in pad=" + cartype);
        System.out.println("estimatedtotalcost in pad=" + estimatedtotalcost);
        System.out.println("estimatedcostperpassenger in pad=" + estimatedcostperpassenger);
        System.out.println("phone in pad=" + phone);
        System.out.println("memo in pad=" + memo);

        //check whether this driver has entered his driver license when registering. If not, forbid posting as driver!
        driverlist = session.selectList("selectuserbyemail", email);
        driverlicense = driverlist.get(0).getDriverlicense();

        if (driverlicense.equals("")) {
            JOptionPane.showMessageDialog(null,
                    "As a driver, you didn't type your driver license when you registered. Please complete information fristly and then come back to post as driver. Thanks for your understanding!",
                    "Message", JOptionPane.ERROR_MESSAGE);
            return "nopost";
        }

        else {
            //check estimated total cost
            String checkcost = "[0-9]+";
            Pattern regex = Pattern.compile(checkcost);
            java.util.regex.Matcher matcher = regex.matcher(estimatedtotalcost);
            boolean isMatched = matcher.matches();

            //check estimated cost per passengre
            java.util.regex.Matcher matcher2 = regex.matcher(estimatedcostperpassenger);
            boolean isMatched2 = matcher2.matches();

            //check phone number
            String checkphone = "[1-9][0-9]{9}";
            Pattern regex2 = Pattern.compile(checkphone);
            java.util.regex.Matcher matcher3 = regex2.matcher(phone);
            boolean isMatched3 = matcher3.matches();

            if (departuredate.equals("") || estimatedtotalcost.equals("")
                    || estimatedcostperpassenger.equals("")) {
                JOptionPane.showMessageDialog(null, "Please fill required information!", "Message",
                        JOptionPane.ERROR_MESSAGE);
            } else if (departure.equals(destination)) {
                JOptionPane.showMessageDialog(null, "Departure and Destination can't be the same city!",
                        "Message", JOptionPane.ERROR_MESSAGE);
            }

            else if (!isMatched) {
                JOptionPane.showMessageDialog(null, "Estimated Total Cost should be numbers!", "Message",
                        JOptionPane.ERROR_MESSAGE);

            }

            else if (!isMatched2) {
                JOptionPane.showMessageDialog(null, "Estimated cost per passenger should be numbers!",
                        "Message", JOptionPane.ERROR_MESSAGE);

            }

            else if (!phone.equals("")) {
                if (!isMatched3) {
                    JOptionPane.showMessageDialog(null, "Phone Number should be 10 numeric digits!", "Message",
                            JOptionPane.ERROR_MESSAGE);
                    return "retype";
                } else {
                    int res;
                    res = JOptionPane.showConfirmDialog(null, "Are you sure you want to post this message?",
                            "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                    if (res == JOptionPane.YES_OPTION) {

                        //search table of postasdriver to set postID
                        postlist = new ArrayList<postasdriver>();
                        postlist = session.selectList("selectAllPostAsDriver");
                        if (postlist.size() == 0) {
                            i = 0;
                        } else {
                            String s = postlist.get(postlist.size() - 1).getPostID();
                            i = Integer.parseInt(s);
                        }

                        //insert new post as driver
                        newpost = new postasdriver();
                        newpost.setPostID(String.valueOf(i + 1));
                        ;
                        newpost.setEmail(email);
                        newpost.setAvailableseats(availableseats);
                        newpost.setCartype(cartype);
                        newpost.setDeparture(departure);
                        newpost.setDestination(destination);
                        newpost.setDeparturedate(departuredate);
                        newpost.setEstimatedcostperpassenger(estimatedcostperpassenger);
                        newpost.setEstimatedtotalcost(estimatedtotalcost);
                        newpost.setPhone(phone);
                        newpost.setMemo(memo);
                        newpost.setEstimatedleavingtime(estimatedleavingtime);
                        newpost.setNumberofappliedpassengers(numberofappliedpassengers);

                        session.insert("insertpostasdriver", newpost);
                        session.commit();
                        JOptionPane.showMessageDialog(null, "Posted Successfully!", "Message",
                                JOptionPane.INFORMATION_MESSAGE);
                        return SUCCESS;
                    } else {
                        return "nopost";
                    }
                }
            }

            else {
                //insert new post as driver
                int res;
                res = JOptionPane.showConfirmDialog(null, "Are you sure you want to post this message?",
                        "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (res == JOptionPane.YES_OPTION) {

                    //search table of postasdriver to set postID
                    postlist = new ArrayList<postasdriver>();
                    postlist = session.selectList("selectAllPostAsDriver");
                    if (postlist.size() == 0) {
                        i = 0;
                    } else {
                        String s = postlist.get(postlist.size() - 1).getPostID();
                        i = Integer.parseInt(s);
                    }

                    //insert new post as driver
                    newpost = new postasdriver();
                    newpost.setPostID(String.valueOf(i + 1));
                    ;
                    newpost.setEmail(email);
                    newpost.setAvailableseats(availableseats);
                    newpost.setCartype(cartype);
                    newpost.setDeparture(departure);
                    newpost.setDestination(destination);
                    newpost.setDeparturedate(departuredate);
                    newpost.setEstimatedcostperpassenger(estimatedcostperpassenger);
                    newpost.setEstimatedtotalcost(estimatedtotalcost);
                    newpost.setPhone(phone);
                    newpost.setMemo(memo);
                    newpost.setEstimatedleavingtime(estimatedleavingtime);

                    session.insert("insertpostasdriver", newpost);
                    session.commit();
                    JOptionPane.showMessageDialog(null, "Posted Successfully!", "Message",
                            JOptionPane.INFORMATION_MESSAGE);
                    return SUCCESS;
                } else {
                    return "nopost";
                }
            }
            return "retype";
        }

    } finally {
        session.close();
    }

}

From source file:action.register.java

public String userregistration() throws IOException {
    System.out.println("name in reg=" + name);
    System.out.println("email in reg=" + email);
    System.out.println("sex in reg=" + sex);
    System.out.println("pw in reg=" + password);
    System.out.println("cpw in reg=" + confirmpassword);
    System.out.println("dob in reg=" + dob);
    System.out.println("dl in reg=" + driverlicense);

    String resource = "orm/configuration.xml";
    Reader reader = Resources.getResourceAsReader(resource);
    SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
    SqlSession session = sessionFactory.openSession();

    try {//  w ww.ja  v a2 s . c om

        String check = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        Pattern regex = Pattern.compile(check);
        java.util.regex.Matcher matcher = regex.matcher(email);
        boolean isMatched = matcher.matches();

        String checkdl = "[0-9]{8}";
        Pattern regex2 = Pattern.compile(checkdl);
        java.util.regex.Matcher matcher2 = regex2.matcher(driverlicense);
        boolean isMatched2 = matcher2.matches();

        userlist = session.selectList("selectuserbyemail", email);

        //check whether the email address is valid

        if (email.equals("") || name.equals("") || password.equals("") || confirmpassword.equals("")
                || sex.equals("") || dob.equals("")) {

            JOptionPane.showMessageDialog(null, "Please fill required information!", "Message",
                    JOptionPane.WARNING_MESSAGE);
        } else if (!confirmpassword.equals(password)) {
            JOptionPane.showMessageDialog(null, "Two passwords don't match, please type again!", "Message",
                    JOptionPane.WARNING_MESSAGE);
        } else if (!isMatched) {
            JOptionPane.showMessageDialog(null, "This email address is invalid!", "Message",
                    JOptionPane.WARNING_MESSAGE);
        }

        else if (!(userlist.isEmpty())) {
            JOptionPane.showMessageDialog(null, "This email address has been registered!", "Message",
                    JOptionPane.WARNING_MESSAGE);
        }

        else if (!driverlicense.equals("")) {
            if (!isMatched2) {
                JOptionPane.showMessageDialog(null, "Driver License should only be 8 numeric numbers!",
                        "Message", JOptionPane.WARNING_MESSAGE);
            }

            else {
                //insert new user
                newuser = new user();
                newuser.setEmail(email);
                newuser.setName(name);
                newuser.setPassword(password);
                newuser.setDob(dob);
                newuser.setDriverlicense(driverlicense);
                newuser.setSex(sex);
                session.insert("insertuserinfo", newuser);
                session.commit();
                JOptionPane.showMessageDialog(null, "Registered Successfully!", "Message",
                        JOptionPane.INFORMATION_MESSAGE);
                return SUCCESS;
            }
        }

        else {
            //insert new user
            newuser = new user();
            newuser.setEmail(email);
            newuser.setName(name);
            newuser.setPassword(password);
            newuser.setDob(dob);
            newuser.setDriverlicense(driverlicense);
            newuser.setSex(sex);
            session.insert("insertuserinfo", newuser);
            session.commit();
            JOptionPane.showMessageDialog(null, "Registered Successfully!", "Message",
                    JOptionPane.INFORMATION_MESSAGE);
            return SUCCESS;
        }

    } finally {
        session.close();
    }

    return "registerfail";

}

From source file:cl.beans.ContactoBean.java

public String guardar() {
    //Asignar un id por defecto
    contacto.setId(-1);// si es -1 es autoincrementable
    SqlSession session = new MyBatisUtil().getSession();
    if (session != null) {
        try {//from ww w . j  a  v  a2s. c om
            session.insert("Contacto.guardarContacto", contacto); //el nombre del namespace
            session.commit();
        } finally {
            session.close();
        }
    } else {
        System.out.println("Error");
    }
    FacesContext.getCurrentInstance().addMessage(null,
            new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Contacto Creado"));
    return "index";
}

From source file:com.beginner.core.dao.DaoSupport.java

License:Apache License

/** 
 * {@inheritDoc}//w  w w  .  j a v a 2  s  .  co  m
 */
@Override
public void batchSave(String str, List objs) throws Exception {
    SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
    //?
    SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
    try {
        if (objs != null) {
            for (int i = 0, size = objs.size(); i < size; i++) {
                sqlSession.insert(str, objs.get(i));
            }
            sqlSession.flushStatements();
            sqlSession.commit();
            sqlSession.clearCache();
        }
    } finally {
        sqlSession.close();
    }
}

From source file:com.company.project.service.UserMapperImpl.java

License:Apache License

@Override
@Transactional("transactionManager")
public int insert(Map user) {
    SqlSession session = sqlSessionFactory.openSession();
    try {// www  . j  a  v a  2s.com
        return session.insert("com.company.project.persistence.UserMapper.insert", user);
    } catch (Exception e) {
        e.printStackTrace();
        session.rollback();
    } finally {
        session.close();
    }

    return 0;
}

From source file:com.company.project.service.UserMapperImpl.java

License:Apache License

@Transactional("txManager")
public int insertx(Map user) {
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    TransactionStatus status = txManager.getTransaction(def);

    SqlSession session = sqlSessionFactory.openSession();
    int result = 0;
    try {//from w  ww.j  a  v  a 2s  .co  m
        result = session.insert("com.company.project.persistence.UserMapper.insert", user);
        txManager.commit(status); // will not insert if this line is removed
        //txManager.rollback(status);
    } catch (Exception e) {
        e.printStackTrace();
        //session.rollback();
        txManager.rollback(status);
    } finally {
        session.close();
    }

    return result;
}

From source file:com.DAO.VehicleDAOImpl.java

@Override
public Integer registerVehicle(Vehicle vehicle) {
    SqlSession session = sqlSessionFactory.openSession();
    try {//from   w w w . j a  va  2s.c o m
        Integer vehicleID = session.insert("Vehicle.insert", vehicle);
        log.info("Vehicle registration ID is : " + vehicle.getVehicleId());
        session.commit();
        if (vehicleID > 0)
            return vehicle.getVehicleId();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        session.close();
    }
    return Integer.MIN_VALUE;
}

From source file:com.glaf.core.db.TableDataManager.java

License:Apache License

public Collection<TableModel> insertAll(String systemName, TableDefinition tableDefinition, String seqNo,
        Collection<TableModel> rows) {
    com.glaf.core.config.Environment.setCurrentSystemName(systemName);
    logger.debug("tableDefinition=" + tableDefinition);
    logger.debug("idColumn=" + tableDefinition.getIdColumn().toString());
    if (tableDefinition.getTableName() != null) {
        tableDefinition.setTableName(tableDefinition.getTableName().toUpperCase());
    }/*from w  w  w .j  a va2  s  .  c o  m*/
    Map<String, Object> colMap = new java.util.HashMap<String, Object>();

    Map<String, String> exprMap = new java.util.HashMap<String, String>();
    List<ColumnDefinition> exprColumns = new java.util.ArrayList<ColumnDefinition>();

    ColumnModel idColumn = new ColumnModel();

    ColumnDefinition idCol = tableDefinition.getIdColumn();
    if (idCol != null && idCol.getColumnName() != null) {
        idColumn.setColumnName(idCol.getColumnName());
        idColumn.setJavaType(idCol.getJavaType());
        idColumn.setValueExpression(idCol.getValueExpression());
        exprColumns.add(idCol);
        exprMap.put(idCol.getColumnName().toLowerCase(), idCol.getValueExpression());
    }

    Iterator<ColumnDefinition> iter = tableDefinition.getColumns().iterator();
    while (iter.hasNext()) {
        ColumnDefinition cell = iter.next();
        if (StringUtils.isNotEmpty(cell.getValueExpression())) {
            exprMap.put(cell.getColumnName().toLowerCase(), cell.getValueExpression());
            exprColumns.add(cell);
        }
    }

    logger.debug("expr map:" + exprMap);

    List<TableModel> inertRows = new java.util.ArrayList<TableModel>();

    logger.debug(" rows size = " + rows.size());
    // logger.debug(" key map: " + keyMap);
    Iterator<TableModel> iterator = rows.iterator();
    while (iterator.hasNext()) {
        TableModel tableData = iterator.next();
        ColumnModel myPK = tableData.getIdColumn();
        ColumnModel pkColumn = new ColumnModel();
        pkColumn.setColumnName(idColumn.getColumnName());
        pkColumn.setJavaType(idColumn.getJavaType());

        for (ColumnModel column : tableData.getColumns()) {
            colMap.put(column.getColumnName(), column.getValue());
        }

        for (ColumnDefinition c : exprColumns) {
            ColumnModel x = new ColumnModel();
            x.setColumnName(c.getColumnName());
            x.setJavaType(c.getJavaType());
            x.setValueExpression(c.getValueExpression());
            tableData.addColumn(x);
        }

        for (ColumnModel cell : tableData.getColumns()) {
            String expr = exprMap.get(cell.getColumnName().toLowerCase());
            if (StringUtils.isNotEmpty(expr)) {
                if (ExpressionConstants.NOW_EXPRESSION.equals(expr)
                        || ExpressionConstants.CURRENT_YYYYMMDD_EXPRESSION.equals(expr)) {
                    if (cell.getDateValue() == null) {
                        cell.setDateValue(new Date());
                        cell.setValue(cell.getDateValue());
                    }
                }
                if (ExpressionConstants.ID_EXPRESSION.equals(expr)) {
                    if (cell.getValue() == null) {
                        if (StringUtils.equals(cell.getJavaType(), "Integer")) {
                            cell.setValue(getEntityService().nextId().intValue());
                        } else if (StringUtils.equals(cell.getJavaType(), "Long")) {
                            cell.setValue(getEntityService().nextId());
                        } else {
                            cell.setValue(getEntityService().getNextId());
                        }
                    }
                }
                if (ExpressionConstants.SEQNO_EXPRESSION.equals(expr)) {
                    cell.setValue(seqNo);
                }
                if (ExpressionConstants.UUID_EXPRESSION.equals(expr)) {
                    cell.setValue(UUID32.getUUID());
                }
            }
        }

        if (myPK != null && myPK.getValue() != null) {
            pkColumn.setValue(myPK.getValue());
        } else {
            if (StringUtils.equals(pkColumn.getJavaType(), "Integer")) {
                pkColumn.setValue(getEntityService().nextId().intValue());
                logger.debug("------------int--------------");
            } else if (StringUtils.equals(pkColumn.getJavaType(), "Long")) {
                pkColumn.setValue(getEntityService().nextId());
            } else {
                pkColumn.setValue(getEntityService().getNextId());
            }
        }

        tableData.removeColumn(pkColumn);
        tableData.addColumn(pkColumn);
        tableData.setIdColumn(pkColumn);

        inertRows.add(tableData);
    }

    if (!inertRows.isEmpty()) {
        logger.debug("inert rows size:" + inertRows.size());
        for (TableModel tableData : inertRows) {
            tableData.setTableName(tableDefinition.getTableName());
            logger.debug(tableData.toString());
            SqlSession sqlSession = null;
            Connection conn = null;
            try {
                conn = DBConnectionFactory.getConnection(systemName);
                conn.setAutoCommit(false);
                sqlSession = getSqlSessionFactory().openSession(ExecutorType.BATCH, conn);
                sqlSession.insert("insertTableData", tableData);
                sqlSession.commit();
                conn.commit();
            } catch (Exception ex) {
                JdbcUtils.rollback(conn);
                logger.error(ex);
                ex.printStackTrace();
                throw new RuntimeException(ex);
            } finally {
                JdbcUtils.close(sqlSession);
                JdbcUtils.close(conn);
            }
        }
    }

    return inertRows;
}

From source file:com.glaf.core.db.TableDataManager.java

License:Apache License

public void insertAllTableData(String systemName, List<TableModel> rows) {
    SqlSession sqlSession = null;
    Connection conn = null;//w w w .  j a v a2 s  .com
    try {
        conn = DBConnectionFactory.getConnection(systemName);
        conn.setAutoCommit(false);
        sqlSession = getSqlSessionFactory().openSession(ExecutorType.BATCH, conn);
        for (TableModel model : rows) {
            if (model.getTableName() != null) {
                model.setTableName(model.getTableName().toUpperCase());
            }
            sqlSession.insert("insertTableData", model);
        }
        sqlSession.commit();
        conn.commit();
    } catch (Exception ex) {
        JdbcUtils.rollback(conn);
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(sqlSession);
        JdbcUtils.close(conn);
    }
}

From source file:com.glaf.core.db.TableDataManager.java

License:Apache License

public void insertTableData(String systemName, List<TableModel> rows) {
    if (rows != null && !rows.isEmpty()) {
        SqlSession sqlSession = null;
        Connection conn = null;/*from  ww  w.  ja va2  s  .  c  o  m*/
        try {
            conn = DBConnectionFactory.getConnection(systemName);
            conn.setAutoCommit(false);
            sqlSession = getSqlSessionFactory().openSession(ExecutorType.BATCH, conn);
            for (TableModel t : rows) {
                if (t.getTableName() != null) {
                    t.setTableName(t.getTableName().toUpperCase());
                }
                sqlSession.insert("insertTableData", t);
            }
            sqlSession.commit();
            conn.commit();
        } catch (Exception ex) {
            JdbcUtils.rollback(conn);
            logger.error(ex);
            ex.printStackTrace();
            throw new RuntimeException(ex);
        } finally {
            JdbcUtils.close(sqlSession);
            JdbcUtils.close(conn);
        }
    }
}