Java Code Examples for org.apache.ibatis.session.SqlSession#selectOne()

The following examples show how to use org.apache.ibatis.session.SqlSession#selectOne() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IncludeTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void testIncludes() throws Exception {
  String resource = "org/apache/ibatis/submitted/includes/MapperConfig.xml";
  Reader reader = Resources.getResourceAsReader(resource);
  SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
  SqlSessionFactory sqlMapper = builder.build(reader);
  assertNotNull(sqlMapper);

  final SqlSession sqlSession = sqlMapper.openSession();
  try {
    final Integer result = sqlSession.selectOne("org.apache.ibatis.submitted.includes.mapper.selectWithProperty");
    Assert.assertEquals(Integer.valueOf(1), result);
  } finally {
    sqlSession.close();
  }
}
 
Example 2
Source File: ComponentTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInsertNestedPasswordFieldOfComplexType() throws Exception {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    //Create User
    User user = new User();
    user.setId(500000L);
    user.setPassword(new EncryptedString("secret"));
    user.setUsername("johnny" + Calendar.getInstance().getTimeInMillis());//random
    user.setAdministrator(true);

    sqlSession.insert("User.insert", user);

    //Retrieve User
    user = (User) sqlSession.selectOne("User.find", user.getId());

    assertNotNull(user.getId());

    sqlSession.rollback();
  } finally {
    sqlSession.close();
  }
}
 
Example 3
Source File: ComponentTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInsertNestedPasswordFieldOfComplexType() throws Exception {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    //Create User
    User user = new User();
    user.setId(500000L);
    user.setPassword(new EncryptedString("secret"));
    user.setUsername("johnny" + Calendar.getInstance().getTimeInMillis());//random
    user.setAdministrator(true);

    sqlSession.insert("User.insert", user);

    //Retrieve User
    user = (User) sqlSession.selectOne("User.find", user.getId());

    assertNotNull(user.getId());

    sqlSession.rollback();
  } finally {
    sqlSession.close();
  }
}
 
Example 4
Source File: FlowerTest.java    From Project with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
      // 加载 xml 文件流
      InputStream is = Resources.getResourceAsStream("MyBatis.xml");
      //使用工厂设计模式
      SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
      //生产SqlSession
      SqlSession session=factory.openSession();

      List<Flower> list = session.selectList("a.b.selAll");
      for (Flower flower : list) {
          System.out.println(flower.toString());
      }

      int count = session.selectOne("a.b.selById");
System.out.println(count);

      //把数据库中哪个列的值当作map的key
      Map<Object, Object> map = session.selectMap("a.b.selectMap", "name");
      System.out.println(map);

      session.close();
  }
 
Example 5
Source File: IncludeTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void testIncludes() throws Exception {
  String resource = "org/apache/ibatis/submitted/includes/MapperConfig.xml";
  Reader reader = Resources.getResourceAsReader(resource);
  SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
  SqlSessionFactory sqlMapper = builder.build(reader);
  assertNotNull(sqlMapper);

  final SqlSession sqlSession = sqlMapper.openSession();
  try {
    final Integer result = sqlSession.selectOne("org.apache.ibatis.submitted.includes.mapper.selectWithProperty");
    Assert.assertEquals(Integer.valueOf(1), result);
  } finally {
    sqlSession.close();
  }
}
 
Example 6
Source File: SqlSessionTestBase.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
protected final void testAndVerifySelectOne() throws Exception {
    // Given
    final String selectOneId = "selectOneId";
    SqlSession sqlSession = getSqlSession();
    // When
    sqlSession.selectOne(selectOneId);
    sqlSession.selectOne(selectOneId, new Object());
    // Then
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    Method selectOne1 = sqlSession.getClass().getDeclaredMethod("selectOne", String.class);
    Method selectOne2 = sqlSession.getClass().getDeclaredMethod("selectOne", String.class, Object.class);
    verifier.verifyTrace(event("MYBATIS", selectOne1, Expectations.cachedArgs(selectOneId)));
    verifier.verifyTrace(event("MYBATIS", selectOne2, Expectations.cachedArgs(selectOneId)));
}
 
Example 7
Source File: ColumnPrefixAutoMappingTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test
public void testCaseInsensitivity() throws Exception {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    Brand brand = sqlSession.selectOne("org.apache.ibatis.submitted.column_prefix.MapperAutoMapping.selectBrandWithProducts", 1);
    assertEquals(Integer.valueOf(1), brand.getId());
    assertEquals(2, brand.getProducts().size());
    assertEquals(Integer.valueOf(10), brand.getProducts().get(0).getId());
    assertEquals("alpha", brand.getProducts().get(0).getName());
  } finally {
    sqlSession.close();
  }
}
 
Example 8
Source File: MybatisTest.java    From Oceanus with Apache License 2.0 5 votes vote down vote up
@Test
public void selectTest() throws SQLException {
	for(long id=1; id<=100; id++){
		SqlSession session = sqlSessionFactory.openSession(true);
		try {
			User user = session.selectOne("com.bj58.oceanus.plugins.mybatis.entity.UserMapper.selectUserByID", Long.valueOf(id));
			System.out.println(user);
		} catch(Exception e){
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
}
 
Example 9
Source File: ColumnPrefixAutoMappingTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test
public void testCaseInsensitivity() throws Exception {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    Brand brand = sqlSession.selectOne("org.apache.ibatis.submitted.column_prefix.MapperAutoMapping.selectBrandWithProducts", 1);
    assertEquals(Integer.valueOf(1), brand.getId());
    assertEquals(2, brand.getProducts().size());
    assertEquals(Integer.valueOf(10), brand.getProducts().get(0).getId());
    assertEquals("alpha", brand.getProducts().get(0).getName());
  } finally {
    sqlSession.close();
  }
}
 
Example 10
Source File: MonitNotifyHistoryDao.java    From JavaTutorial with Apache License 2.0 5 votes vote down vote up
public MonitNotifyHistory selectByPrimaryKey(Long recordId) {
    SqlSession session = _ssFactory.openSession();
    MonitNotifyHistory result = null;
    try {
        result = session.selectOne(assembleStatement("selectByPrimaryKey"), recordId);
    } finally {
        close(session);
    }
    
    return result;
}
 
Example 11
Source File: NestedResultHandlerMultipleAssociationTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test
public void success() throws Exception {
  SqlSession sqlSession = sqlSessionFactory.openSession();

  ParentBean parent = sqlSession.selectOne("selectParentBeanById", 2);

  // If you only select the Parent2 it works
  for (Binome<ChildBean, ChildBean> childs : parent.getChilds()) {
    Assert.assertNotNull(childs);
    Assert.assertNotNull(childs.getOne());
    Assert.assertNotNull(childs.getTwo());
  }
  sqlSession.close();
}
 
Example 12
Source File: ValueInMapTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test(expected=PersistenceException.class)
public void shouldWorkWithAList() {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    List<String> list = new ArrayList<String>();
    list.add("users");
    Integer count = sqlSession.selectOne("count2",list);
    Assert.assertEquals(new Integer(1), count);
  } finally {
    sqlSession.close();
  }
}
 
Example 13
Source File: ValueInMapTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test // issue #165
public void shouldWorkWithAPropertyNamedValue() {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    Map<String, String> map = new HashMap<String, String>();
    map.put("table", "users");
    map.put("column", "name");
    map.put("value", "User1");
    Integer count = sqlSession.selectOne("count", map);
    Assert.assertEquals(new Integer(1), count);
  } finally {
    sqlSession.close();
  }
}
 
Example 14
Source File: RawSqlSourceTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private void test(String statement, Class<? extends SqlSource> sqlSource) {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    Assert.assertEquals(sqlSource, sqlSession.getConfiguration().getMappedStatement(statement).getSqlSource().getClass());
    String sql = sqlSession.getConfiguration().getMappedStatement(statement).getSqlSource().getBoundSql('?').getSql();
    Assert.assertEquals("select * from users where id = ?", sql);
    User user = sqlSession.selectOne(statement, 1);
    Assert.assertEquals("User1", user.getName());
  } finally {
    sqlSession.close();
  }
}
 
Example 15
Source File: NonFullyQualifiedNamespaceTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test
public void testCrossReferenceXmlConfig() throws Exception {
    Reader configReader = Resources
            .getResourceAsReader("org/apache/ibatis/submitted/xml_external_ref/NonFullyQualifiedNamespaceConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configReader);
    configReader.close();

    Configuration configuration = sqlSessionFactory.getConfiguration();

    MappedStatement selectPerson = configuration.getMappedStatement("person namespace.select");
    assertEquals(
            "org/apache/ibatis/submitted/xml_external_ref/NonFullyQualifiedNamespacePersonMapper.xml",
            selectPerson.getResource());

    Connection conn = configuration.getEnvironment().getDataSource().getConnection();
    initDb(conn);

    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
        Person person = (Person) sqlSession.selectOne("person namespace.select", 1);
        assertEquals((Integer)1, person.getId());
        assertEquals(2, person.getPets().size());
        assertEquals((Integer)2, person.getPets().get(1).getId());

        Pet pet = (Pet) sqlSession.selectOne("person namespace.selectPet", 1);
        assertEquals(Integer.valueOf(1), pet.getId());

        Pet pet2 = (Pet) sqlSession.selectOne("pet namespace.select", 3);
        assertEquals((Integer)3, pet2.getId());
        assertEquals((Integer)2, pet2.getOwner().getId());
    }
    finally {
        sqlSession.close();
    }
}
 
Example 16
Source File: IDAllocDaoImpl.java    From Leaf with Apache License 2.0 5 votes vote down vote up
@Override
public LeafAlloc updateMaxIdByCustomStepAndGetLeafAlloc(LeafAlloc leafAlloc) {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
        sqlSession.update("com.sankuai.inf.leaf.segment.dao.IDAllocMapper.updateMaxIdByCustomStep", leafAlloc);
        LeafAlloc result = sqlSession.selectOne("com.sankuai.inf.leaf.segment.dao.IDAllocMapper.getLeafAlloc", leafAlloc.getKey());
        sqlSession.commit();
        return result;
    } finally {
        sqlSession.close();
    }
}
 
Example 17
Source File: IDAllocDaoImpl.java    From Leaf with Apache License 2.0 5 votes vote down vote up
@Override
public LeafAlloc updateMaxIdAndGetLeafAlloc(String tag) {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
        sqlSession.update("com.sankuai.inf.leaf.segment.dao.IDAllocMapper.updateMaxId", tag);
        LeafAlloc result = sqlSession.selectOne("com.sankuai.inf.leaf.segment.dao.IDAllocMapper.getLeafAlloc", tag);
        sqlSession.commit();
        return result;
    } finally {
        sqlSession.close();
    }
}
 
Example 18
Source File: IDAllocDaoImpl.java    From SpringMVC-Project with MIT License 5 votes vote down vote up
@Override
public LeafAlloc updateMaxIdByCustomStepAndGetLeafAlloc(LeafAlloc leafAlloc) {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
        sqlSession.update("com.doodl6.springmvc.service.leaf.segment.dao.IDAllocMapper.updateMaxIdByCustomStep", leafAlloc);
        LeafAlloc result = sqlSession.selectOne("com.doodl6.springmvc.service.leaf.segment.dao.IDAllocMapper.getLeafAlloc", leafAlloc.getKey());
        sqlSession.commit();
        return result;
    } finally {
        sqlSession.close();
    }
}
 
Example 19
Source File: MybatisTester.java    From J2Cache with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        String resource = "/mybatis.xml";
        InputStream inputStream = MybatisTester.class.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            System.out.println("mybatis init.");
            /*
            Blog blog = new Blog();
            blog.setId(100);
            blog.setTitle("博客标题1");
            blog.setBody("博客内容1");
            session.insert("new", blog);

            System.out.println("blog inserted");
            */
            for(int i=0;i<10;i++) {
                Blog db = session.selectOne("read", 100);
                System.out.printf("id=%d,title=%s,body=%s%n", db.getId(), db.getTitle(), db.getBody());
                session.commit();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
            System.exit(0);
        }

    }
 
Example 20
Source File: DataTableDao.java    From sso-oauth2 with Apache License 2.0 3 votes vote down vote up
public int getListForPageCount(String statement, Map queryParam) {
	SqlSession sqlSession = sqlSessionFactory.openSession();

	Integer count = sqlSession.selectOne(statement, queryParam);

	sqlSession.close();

	return count;
}