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

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

Introduction

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

Prototype

int delete(String statement, Object parameter);

Source Link

Document

Execute a delete statement.

Usage

From source file:in.flipbrain.dao.MyBatisDao.java

License:Apache License

public void saveQuestion(QuestionDto dto) {
    SqlSession session = sqlSessionFactory.openSession();
    try {/*from  ww w.j a v a2  s.co m*/
        if (dto.questionId < 1 && !dto.isDeleted()) {
            session.insert("insertQuestion", dto);
        } else if (dto.isDeleted()) {
            session.delete("deleteQuestion", dto);
        } else {
            session.update("updateQuestion", dto);
        }
        for (AnswerOptionDto opt : dto.answerOptions) {
            opt.questionId = dto.questionId;
            opt.author = dto.author;
            if (opt.answerOptId < 1 && !opt.isDeleted()) {
                session.insert("insertAnswerOption", opt);
            } else if (opt.isDeleted()) {
                session.delete("deleteAnswerOption", opt);
            } else {
                session.update("updateAnswerOption", opt);
            }
        }
        session.commit();
    } finally {
        session.close();
    }
}

From source file:in.flipbrain.dao.MyBatisDao.java

License:Apache License

public void saveAssessment(AssessmentDto dto) {
    SqlSession session = sqlSessionFactory.openSession();
    try {//w  ww.  ja  v a2 s .c o m
        if (dto.assessId < 1 && !dto.isDeleted()) {
            session.insert("insertAssessment", dto);
        } else if (dto.isDeleted()) {
            session.delete("deleteAssessment", dto);
        } else {
            session.update("updateAssessment", dto);
        }

        for (AssessmentQuestionDto q : dto.questions) {
            q.assessId = dto.assessId;
            if (q.assessQuestId < 1 && !q.isDeleted()) {
                session.insert("insertAssessmentQuestion", q);
            } else if (q.isDeleted()) {
                session.delete("deleteAssessmentQuestion", q);
            } else {
                session.update("updateAssessmentQuestion", q);
            }
        }
        session.commit();
    } finally {
        session.close();
    }
}

From source file:in.flipbrain.dao.MyBatisDao.java

License:Apache License

protected <T> int saveEntity(String stmtId, T dto, Operation op) {
    int rows = 0;
    SqlSession session = sqlSessionFactory.openSession();
    try {//from  www . ja  va 2s .  c o m
        logActivity(session);
        switch (op) {
        case Del:
            rows = session.delete(stmtId, dto);
            break;
        case Ins:
            rows = session.insert(stmtId, dto);
            break;
        case Upd:
            rows = session.update(stmtId, dto);
            break;
        }
        session.commit();
    } finally {
        session.close();
    }
    return rows;
}

From source file:io.starter.datamodel.ContentData.java

License:Open Source License

/**
 * //from   w w w.java 2s.  c  o m
 * @param servletRequest
 * @param servletResponse
 * @return
 * @throws JSONException
 * @throws IOException
 * @throws ServletException
 */
@DELETE
@Path("delete")
public void delete(@PathParam("contentId") int id, @Context HttpServletRequest servletRequest,
        @Context HttpServletResponse servletResponse) throws IOException, ServletException {

    // TODO: checkaccess
    // Content cxdel = getContentObject(servletRequest, servletResponse);
    // String contentToDelete = cxdel.getUrl();

    // TODO: S3FS is our friend
    // S3FS s3fs = new S3FS();
    // s3fs.deleteFile(S3_STARTER_MEDIA_BUCKET,);

    SqlSession session = (SqlSession) servletRequest.getAttribute(SESSION_VAR_SQLSESSION);

    try {

        // delete content acls
        AclExample a = new AclExample();
        Criteria c = a.createCriteria();
        c.andTargetIdEqualTo(id);
        c.andTargetTypeEqualTo(SystemConstants.SECURITY_TARGET_TYPE_CONTENT);

        session.delete("io.starter.dao.AclMapper.deleteByExample", a);
        session.commit();

        // delete content record
        session.delete("io.starter.dao.ContentMapper.deleteByPrimaryKey", id);
        session.commit();

    } catch (Exception e) {
        // if there are cascading FK constraints then we need to mark this
        // content item deleted (not actually delete it)
        // this way we preserve the integrity of the system
        // TODO: discuss handling deletion of content in re: orphan data

        Content cxdel = getContentObject(servletRequest, id);

        session = (SqlSession) servletRequest.getAttribute(SESSION_VAR_SQLSESSION);

        try {
            cxdel.setFlag(FLAG_DELETED);
            session.update("io.starter.dao.ContentMapper.updateByPrimaryKey", cxdel);
            session.commit();
        } catch (Exception x) {
            Logger.error("Total failure in ContentData.delete trying to mark content item as deleted: "
                    + x.toString());
            // hmmm total failure
        }

    }

    super.deleteds.add(id);
    // update caches
    super.removeContentFromCaches(id, servletRequest);

}

From source file:io.starter.datamodel.ContentData.java

License:Open Source License

/**
 * do the work of deleting all existing acls for content, inserting a new
 * owner acl, and optionally inserting necessary new ACL(s) based on the
 * OP_TYPE// w  ww.  ja  v  a 2 s . com
 * 
 * @param optype
 * @param servletRequest
 * @param id
 * @return
 * @throws ServletException
 */
private String resetAclsForContent(int optype, ServletRequest servletRequest, Integer id)
        throws ServletException {
    // DELETE all ACLs except the User's OWNER ACL
    Object u = servletRequest.getAttribute(SESSION_VAR_USER);

    if (u == null)
        throw new ServletException("No User in Request -- Anonymous users cannot modify content permissions.");

    User user = (User) u;
    int uid = user.getId();

    user.clearCachedAuthorizationForAllUsers();

    SqlSession session = (SqlSession) servletRequest.getAttribute(SESSION_VAR_SQLSESSION);
    int rowsDeleted = 0;

    // delete content acls
    AclExample ax = new AclExample();
    Criteria c = ax.createCriteria();
    c.andTargetIdEqualTo(id);
    c.andTargetTypeEqualTo(SECURITY_TARGET_TYPE_CONTENT);
    session.delete("io.starter.dao.AclMapper.deleteByExample", ax);
    session.commit();

    Acl a = new Acl();
    // give permission to current session user -- only one allowed to do
    // this
    a.setPrincipleId(user.getId());
    a.setPrincipleType(SECURITY_PRINCIPAL_TYPE_USER);

    // allow them to
    a.setPermission(SECURITY_ACL_OWNER);

    // to this thing
    a.setTargetId(id);
    a.setTargetType(SECURITY_TARGET_TYPE_CONTENT);

    int rowsInserted = session.insert("io.starter.dao.AclMapper.insert", a);

    if (rowsInserted < 1)
        throw new ServletException("Could not make Content object private: setting Owner ACL failed.");

    if (optype == OPTYPE_SET_PUBLIC) { // make public

        Acl ae = new Acl();
        // give permission to current session user -- only one allowed
        // to do
        // this
        ae.setPrincipleId(SECURITY_ROLE_EVERYONE);
        ae.setPrincipleType(SECURITY_PRINCIPAL_TYPE_ROLE);

        // allow them to
        ae.setPermission(SystemConstants.SECURITY_ACL_APPEND); // required
        // to allow
        // comments/rating

        // to this thing
        ae.setTargetId(id);
        ae.setTargetType(SECURITY_TARGET_TYPE_CONTENT);

        rowsInserted = session.insert("io.starter.dao.AclMapper.insert", ae);
        session.commit();

        ae = new Acl();
        ae.setPrincipleId(SECURITY_ROLE_EVERYONE);
        ae.setPrincipleType(SECURITY_PRINCIPAL_TYPE_ROLE);

        // allow them to
        ae.setPermission(SystemConstants.SECURITY_ACL_READ); // need to see

        // to this thing
        ae.setTargetId(id);
        ae.setTargetType(SECURITY_TARGET_TYPE_CONTENT);

        rowsInserted += session.insert("io.starter.dao.AclMapper.insert", ae);
        session.commit();
        if (rowsInserted < 2)
            throw new ServletException(
                    "Could not make Content object private: setting Everyone READ-ONLY and APPEND ACLs failed.");

    } else if (optype == OPTYPE_SET_TAKEOVER_OWNERSHIP) { // take over
        // ownership
        // (administrators)
        if (!user.isAdmin())
            throw new ServletException(
                    "Could not take over Content object ownership: Only Administrators can do this.");

        Acl ax1 = new Acl();
        // give permission to current session user -- only one allowed
        // to do
        // this
        ax1.setPrincipleId(1);
        ax1.setPrincipleType(SECURITY_PRINCIPAL_TYPE_USER);

        // allow them to
        ax1.setPermission(SECURITY_ACL_OWNER);

        // to this thing
        ax1.setTargetId(id);
        ax1.setTargetType(SECURITY_TARGET_TYPE_CONTENT);

        rowsInserted = session.insert("io.starter.dao.AclMapper.insert", ax1);

        if (rowsInserted < 1)
            throw new ServletException(
                    "Could not take over Content object ownership: setting Owner ACL failed.");

    }
    session.commit();

    // return the result
    return "true";
}

From source file:io.starter.TestContent.java

License:Open Source License

/**
 * test inserting some data/*ww  w. ja  v a2 s.c o  m*/
 * 
 */
@Test
public void testInsertAndMarkContentTrashed() {

    Content content = new Content();
    content.setUserId(42);
    content.setAuthor(42);
    content.setAuthorDevice(1);
    content.setCopyright("Copyright 2013. All rights reserved");
    content.setDescription("CheezBurger Cat");
    content.setLicense("CC");
    content.setMimeType("text/plain");
    content.setUrl("http://www.hazcheezburger.com");
    content.setFlag(FLAG_STAR);
    content.setPostDate(new java.util.Date(System.currentTimeMillis()));
    // ContentMapper.insert(content);
    SqlSession session = sqlSessionFactory.openSession(true);
    session.insert("io.starter.dao.ContentMapper.insert", content);

    Integer id = content.getId();
    if (id == null)
        fail("Content insertion returns null ID");

    try {
        Content ccx = session.selectOne("io.starter.dao.ContentMapper.selectObjByPrimaryKey", id);
        User u = ccx.getUser();
        if (u == null)
            fail("User is null for content object inserted with user_id = 1. Content ID: " + id);

        String s = ccx.getDescription();
        if (s == null)
            fail("Failed to insert Content ID: " + id);
    } catch (Exception x) {
        fail("Exception fetching content from new Content ID: " + id);
    }

    // test deletion of that new content
    // content.setFlag(FLAG_DELETED);

    session = sqlSessionFactory.openSession(true);

    session.delete("io.starter.dao.ContentMapper.deleteByPrimaryKey", content);

    try {
        Content ccd = session.selectOne("io.starter.dao.ContentMapper.selectByPrimaryKey", id);

        if (ccd.getFlag() != FLAG_DELETED)
            fail("Failed to mark deleted newly inserted Content ID: " + id);
    } catch (Exception x) {
        // good!
    }
    session.close();

}

From source file:io.starter.TestContent.java

License:Open Source License

/**
 * test inserting some data/*from   w ww. java2  s.  c  o m*/
 * 
 */
@Test
public void testInsertAndDeleteContent() {
    Content content = new Content();
    content.setAuthor(1);
    content.setAuthorDevice(1);
    content.setCopyright("Copyright 2013. All rights reserved");
    content.setDescription("CheezBurger Cat");
    content.setLicense("CC");
    content.setFlag(FLAG_STAR);
    content.setMimeType("text/plain");
    content.setUrl("http://www.hazcheezburger.com");
    content.setPostDate(new java.util.Date(System.currentTimeMillis()));

    sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory();
    SqlSession session = sqlSessionFactory.openSession(true);
    session.insert("io.starter.dao.ContentMapper.insert", content);

    Integer id = content.getId();
    if (id == null)
        fail("Content insertion returns null ID");

    try {
        Content ccx = session.selectOne("io.starter.dao.ContentMapper.selectByPrimaryKey", id);

        String s = ccx.getDescription();
        if (s == null)
            fail("Failed to insert Content ID: " + id);
    } catch (Exception x) {
        fail("Exception fetching content from new Content ID: " + id);
    }

    // test deletion of that new content
    Content cxdel = new Content();
    cxdel.setId(id);

    session = sqlSessionFactory.openSession(true);
    session.delete("io.starter.dao.ContentMapper.deleteByPrimaryKey", cxdel);

    session.close();

    try {
        Content ccd = session.selectOne("io.starter.dao.ContentMapper.selectByPrimaryKey", id);

        String s = ccd.getDescription();
        if (s != null)
            fail("Failed to delete inserted Content ID: " + id);
    } catch (Exception x) {
        // good!
    }

}

From source file:io.starter.TestContent.java

License:Open Source License

/**
 * test cpntent ownership ratings/*  ww  w.ja  va2  s .  c om*/
 * 
 * @throws Exception
 */
@Test
public void testOwnershipPermissions() throws Exception {

    Content content = new Content();
    content.setAuthor(42);
    content.setUserId(42);
    content.setAuthorDevice(1);
    content.setCopyright("Copyright 2014. All rights reserved");
    content.setDescription("TEST Starter Content");
    content.setLicense("CC");

    content.setFlag(FLAG_STAR);
    content.setMimeType("text/html");
    content.setUrl("http://$$PROJECT_DOMAIN$$");
    content.setPostDate(new java.util.Date(System.currentTimeMillis()));
    sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory();
    SqlSession session = sqlSessionFactory.openSession(true);
    session.insert("io.starter.dao.ContentMapper.insert", content);
    session.commit();

    Integer id = content.getId();
    assertTrue(id != null);

    Content ccx = session.selectOne("io.starter.dao.ContentMapper.selectObjByPrimaryKey", id);

    User user = ccx.getUser();
    assertTrue(ccx.getUserId() == 42);

    // assert that contact info is stripped from this
    assertEquals(null, user.getEmail());

    // and that we got the right user
    assertEquals("test", user.getUsername());

    // 1. Build the Subject instance for the test to run:
    Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();

    // 2. Bind the subject to the current thread:
    setSubject(subjectUnderTest);
    // see /login.jsp for these form fields
    String username = "test";
    String password = API_CRYPT_KEY;

    // create a UsernamePasswordToken using the
    // username and password provided by the user
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);

    // get the user (aka subject) associated with this request.

    Subject subject = SecurityUtils.getSubject();

    try {
        subject.checkPermission("thing:action");
        fail("User INCORRECTLY has permission thing:action");
    } catch (AuthorizationException x) {
        // GOOD!
    }

    subject.login(token);
    user.setSubject(subject);

    ContentData.setContentOwnerPermissions(content, user, session);

    WildcardPermission owner = new WildcardPermission(SystemConstants.SECURITY_TARGET_TYPE_CONTENT + ":"
            + SystemConstants.SECURITY_ACL_OWNER + ":" + content.getId());

    assert (user.checkAccess(owner));

    // test deletion of that new content
    session = sqlSessionFactory.openSession(true);
    session.delete("io.starter.dao.ContentMapper.deleteByPrimaryKey", ccx);

    try {
        Content ccd = session.selectOne("io.starter.dao.ContentMapper.selectByPrimaryKey", id);

        String s1 = ccd.getDescription();
        if (s1 != null)
            fail("Failed to delete inserted Content ID: " + id);
    } catch (Exception x) {
        // good!
    }

    session.close();
}

From source file:io.starter.TestContent.java

License:Open Source License

/**
 * test cpntent ratings!// ww w.  jav a2  s  .com
 * 
 * @throws Exception
 */
@Test
@Ignore
// we don't select ratings objects anymore... revisit someday
public void testRatings() throws Exception {
    Content content = new Content();
    content.setAuthor(42);
    content.setUserId(42);
    content.setAuthorDevice(1);
    content.setCopyright("Copyright 2013. All rights reserved");
    content.setDescription("TEST Ostrich Pillow");
    content.setLicense("CC");

    content.setFlag(FLAG_STAR);
    content.setMimeType("text/html");
    content.setUrl("http://www.ostrichpillow.com");

    content.setPostDate(new java.util.Date(System.currentTimeMillis()));
    sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory();
    SqlSession session = sqlSessionFactory.openSession(true);
    session.insert("io.starter.dao.ContentMapper.insert", content);

    Integer id = content.getId();
    assertTrue(id != null);

    // rate the bastard
    ContentRating rx = new ContentRating();
    rx.setContentId(id);
    rx.setFlag(0);
    rx.setRaterId(1);
    rx.setReview("that kinda sucked");
    rx.setType(1);
    rx.setValue((long) 3);
    session.insert("io.starter.dao.ContentRatingMapper.insert", rx);

    session.commit();

    Content ccx = session.selectOne("io.starter.dao.ContentMapper.selectObjByPrimaryKey", id);

    String s = ccx.getDescription();
    if (s == null)
        fail("Failed to insert Content ID: " + id);

    ArrayList<ContentRating> ratings = ccx.getRatings();
    ContentRating rating = ratings.get(0);
    assertEquals("that kinda sucked", rating.getReview());

    User user = ccx.getUser();
    assertTrue(ccx.getUserId() == 1);
    assertEquals("john@$$PROJECT_DOMAIN$$", user.getEmail());

    // test deletion of that new content

    session = sqlSessionFactory.openSession(true);
    session.delete("io.starter.dao.ContentRatingMapper.deleteByPrimaryKey", rx);

    session.delete("io.starter.dao.ContentMapper.deleteByPrimaryKey", ccx);

    session.close();

    try {
        Content ccd = session.selectOne("io.starter.dao.ContentMapper.selectByPrimaryKey", id);

        String s1 = ccd.getDescription();
        if (s1 != null)
            fail("Failed to delete inserted Content ID: " + id);
    } catch (Exception x) {
        // good!
    }

    session.close();
}

From source file:net.hasor.db.orm.mybatis3.SqlExecutorTemplate.java

License:Apache License

public int delete(final String statement, final Object parameter) throws SQLException {
    return this.execute(new SqlSessionCallback<Integer>() {
        public Integer doSqlSession(SqlSession sqlSession) {
            return sqlSession.delete(statement, parameter);
        }//from  ww w  .j ava  2s .  c om
    });
}