Java Code Examples for org.apache.ibatis.session.SqlSessionFactory#openSession()

The following examples show how to use org.apache.ibatis.session.SqlSessionFactory#openSession() . 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: MultipleCrossIncludeTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private void testCrossReference(SqlSessionFactory sqlSessionFactory) throws Exception {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    MultipleCrossIncludePersonMapper personMapper = sqlSession.getMapper(MultipleCrossIncludePersonMapper.class);
    Person person = personMapper.select(1);
    assertEquals((Integer)1, person.getId());
    assertEquals(2, person.getPets().size());
    assertEquals((Integer)2, person.getPets().get(1).getId());

    Pet pet = personMapper.selectPet(1);
    assertEquals(Integer.valueOf(1), pet.getId());

    MultipleCrossIncludePetMapper petMapper = sqlSession.getMapper(MultipleCrossIncludePetMapper.class);
    Pet pet2 = petMapper.select(3);
    assertEquals((Integer)3, pet2.getId());
    assertEquals((Integer)2, pet2.getOwner().getId());
  } finally {
    sqlSession.close();
  }
}
 
Example 2
Source File: InsertTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertAnnotated() throws Exception {
  Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/keycolumn/MapperConfig.xml");
  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    InsertMapper mapper = sqlSession.getMapper(InsertMapper.class);
    Name name = new Name();
    name.setFirstName("Fred");
    name.setLastName("Flintstone");

    int rows = mapper.insertNameAnnotated(name);

    assertNotNull(name.getId());
    assertEquals(1, rows);
  } finally {
    sqlSession.close();
  }
}
 
Example 3
Source File: InsertTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Ignore // Not supported yet in PostgreSQL
@Test
public void testInsertMappedBatch() throws Exception {
  Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/keycolumn/MapperConfig.xml");
  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
  try {
    InsertMapper mapper = sqlSession.getMapper(InsertMapper.class);
    Name name = new Name();
    name.setFirstName("Fred");
    name.setLastName("Flintstone");
    mapper.insertNameMapped(name);
    Name name2 = new Name();
    name2.setFirstName("Wilma");
    name2.setLastName("Flintstone");
    mapper.insertNameMapped(name2);
    List<BatchResult> batchResults = sqlSession.flushStatements();
    assertNotNull(name.getId());
    assertNotNull(name2.getId());
    assertEquals(1, batchResults.size());
  } finally {
    sqlSession.close();
  }
}
 
Example 4
Source File: InsertTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertMapped() throws Exception {
  Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/keycolumn/MapperConfig.xml");
  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    InsertMapper mapper = sqlSession.getMapper(InsertMapper.class);
    Name name = new Name();
    name.setFirstName("Fred");
    name.setLastName("Flintstone");

    int rows = mapper.insertNameMapped(name);

    assertNotNull(name.getId());
    assertEquals(1, rows);
  } finally {
    sqlSession.close();
  }
}
 
Example 5
Source File: BatchInsertMain.java    From blog with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	String resource = "mybatis-config2.xml";
	InputStream inputStream = Resources.getResourceAsStream(resource);
	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

	FileAnalysis fileAnalysis = new FileAnalysis();
	SqlSession session = sqlSessionFactory.openSession();
	try {
		FielAnalysisMapper mapper = session.getMapper(FielAnalysisMapper.class);
		fileAnalysis = mapper.selectFileAnalysis("01");
		session.commit();
	} finally {
		session.close();
	}

	FileAnalysisInsert fileAnalysisInsert = new FileAnalysisInsert(sqlSessionFactory);
	fileAnalysisInsert.batchInsertOrder(fileAnalysis);

}
 
Example 6
Source File: InsertTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Ignore // Not supported yet in PostgreSQL
@Test
public void testInsertMappedBatch() throws Exception {
  Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/keycolumn/MapperConfig.xml");
  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
  try {
    InsertMapper mapper = sqlSession.getMapper(InsertMapper.class);
    Name name = new Name();
    name.setFirstName("Fred");
    name.setLastName("Flintstone");
    mapper.insertNameMapped(name);
    Name name2 = new Name();
    name2.setFirstName("Wilma");
    name2.setLastName("Flintstone");
    mapper.insertNameMapped(name2);
    List<BatchResult> batchResults = sqlSession.flushStatements();
    assertNotNull(name.getId());
    assertNotNull(name2.getId());
    assertEquals(1, batchResults.size());
  } finally {
    sqlSession.close();
  }
}
 
Example 7
Source File: CmsCmProcessorTest.java    From oneops with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    System.out.println("Starting up CmsCmProcessor tests");
 String resource = "mybatis-config.xml";
 Reader reader = Resources.getResourceAsReader( resource );
 SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(reader);
    session = sf.openSession();
 clazzMapper = session.getMapper(ClazzMapper.class);
    ciMapper = session.getMapper(CIMapper.class);
    mdValidator = new CmsMdValidator();
    cmValidator = new CmsCmValidator();
 mdProcessor = new CmsMdProcessor();
 mdProcessor.setClazzMapper( clazzMapper );
 mdProcessor.setMdValidator(mdValidator);
    cmProcessor = new CmsCmProcessor();
    cmProcessor.setCiMapper(ciMapper);
    cmProcessor.setMdProcessor(mdProcessor);
    cmProcessor.setCmValidator(cmValidator);
    RelationMapper relationMapper=session.getMapper(RelationMapper.class);
    mdProcessor.setRelationMapper(relationMapper);
    
}
 
Example 8
Source File: XmlExternalRefTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private void testCrossReference(SqlSessionFactory sqlSessionFactory) throws Exception {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
    Person person = personMapper.select(1);
    assertEquals((Integer)1, person.getId());
    assertEquals(2, person.getPets().size());
    assertEquals((Integer)2, person.getPets().get(1).getId());

    Pet pet = personMapper.selectPet(1);
    assertEquals(Integer.valueOf(1), pet.getId());

    PetMapper petMapper = sqlSession.getMapper(PetMapper.class);
    Pet pet2 = petMapper.select(3);
    assertEquals((Integer)3, pet2.getId());
    assertEquals((Integer)2, pet2.getOwner().getId());
  } finally {
    sqlSession.close();
  }
}
 
Example 9
Source File: InsertTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertAnnotated() throws Exception {
  Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/keycolumn/MapperConfig.xml");
  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    InsertMapper mapper = sqlSession.getMapper(InsertMapper.class);
    Name name = new Name();
    name.setFirstName("Fred");
    name.setLastName("Flintstone");

    int rows = mapper.insertNameAnnotated(name);

    assertNotNull(name.getId());
    assertEquals(1, rows);
  } finally {
    sqlSession.close();
  }
}
 
Example 10
Source File: XmlExternalRefTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
private void testCrossReference(SqlSessionFactory sqlSessionFactory) throws Exception {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
    Person person = personMapper.select(1);
    assertEquals((Integer)1, person.getId());
    assertEquals(2, person.getPets().size());
    assertEquals((Integer)2, person.getPets().get(1).getId());

    Pet pet = personMapper.selectPet(1);
    assertEquals(Integer.valueOf(1), pet.getId());

    PetMapper petMapper = sqlSession.getMapper(PetMapper.class);
    Pet pet2 = petMapper.select(3);
    assertEquals((Integer)3, pet2.getId());
    assertEquals((Integer)2, pet2.getOwner().getId());
  } finally {
    sqlSession.close();
  }
}
 
Example 11
Source File: MybatisHelper.java    From cjs_ssms with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 根据mybatis配置获取SqlSession,这个方法在测试Mapper时候不是很靠谱,需检测
 *
 * 此方法未设定mapper一些必要设定的属性,执行会报错 不要使用
 *
 * @return
 * @throws IOException
 */
@Deprecated
public static SqlSession session() throws IOException {
  String resource = "database/mybatis-config-javaapi.xml";
  InputStream inputStream = Resources.getResourceAsStream(resource);
  SqlSessionFactory sqlSessionFactory = (new SqlSessionFactoryBuilder()).build(inputStream);
  SqlSession sqlSession = sqlSessionFactory.openSession();
  return sqlSession;
}
 
Example 12
Source File: MybatisCRUDTest.java    From code with Apache License 2.0 5 votes vote down vote up
/**
 * mybatis数据源
 *  PooledDataSource中找到popConnection()方法
 */
@Test
public void testSql() throws Exception {
    InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
    SqlSession sqlSession = factory.openSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    User user = userMapper.findUserById(42);
    System.out.println(user);

    // 释放资源
    sqlSession.close();
    in.close();
}
 
Example 13
Source File: UserMain.java    From blog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
	String resource = "mybatis-config.xml";
	InputStream inputStream = Resources.getResourceAsStream(resource);
	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

	// 方式一
	SqlSession session1 = sqlSessionFactory.openSession();
	User user = new User();
	user.setId(102);
	user.setSex(Sex.FEMALE);
	user.setName("zhaohui");
	try {
		session1.insert("insertUser", user);
		session1.commit();
	} finally {
		session1.close();
	}

	SqlSession session2 = sqlSessionFactory.openSession();
	try {
		UserMapper userMapper = session2.getMapper(UserMapper.class);
		User user2 = userMapper.getUser(102);
		System.out.println(user2.toString());
	} finally {
		session2.close();
	}

}
 
Example 14
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 15
Source File: PeopleServiceImpl.java    From Project with Apache License 2.0 5 votes vote down vote up
public List<People> selectAll() throws IOException {
    // MyBatis 默认不加载配置文件,因此需要先加载配置文件,返回整个配置文件的流对象
    // 在数据访问层处理异常和在控制器中处理异常,一般在 service 中只抛出异常;
    InputStream inputStream = Resources.getResourceAsStream("MyBatis.xml");
    // 前面是工厂       实例化工厂对象时使用的是构建者设计模式   它的名称标志:后面有Builder
    // 构建者设计模式意义: 简化对象实例化过程
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
    // 整个 sqlsession 就是 MyBatis 中 API 封装的对象,增删改查都在里面
    SqlSession session = factory.openSession();
    List<People> list = session.selectList("com.gjxaiou.mapper.PeopleMapper.selAll");
    session.close();
    return list;
}
 
Example 16
Source File: TestBatisXML.java    From java-course-ee with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    String resource = "Configuration.xml";
    Reader reader = Resources.getResourceAsReader(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

    SqlSession session = sqlSessionFactory.openSession();
    try {
        Region region = new Region();
        region.setRegionName("12345");

        session.insert("ibatis.RegionMapper.insertRegion", region);
        session.commit();

        System.out.println("Region ID: " + region.getRegionId());

        findAndGet(session);

        region.setRegionName("54321");
        session.update("ibatis.RegionMapper.updateRegion", region);
        session.commit();
        findAndGet(session);

        session.delete("ibatis.RegionMapper.deleteRegion", region.getRegionId());
        session.commit();
        findAndGet(session);

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

}
 
Example 17
Source File: MultipleReverseIncludeTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private void testMultipleReverseIncludes(SqlSessionFactory sqlSessionFactory) throws Exception {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    MultipleReverseIncludePersonMapper personMapper = sqlSession.getMapper(MultipleReverseIncludePersonMapper.class);
    Person person = personMapper.select(1);
    assertEquals((Integer)1, person.getId());
    assertEquals("John", person.getName());

  } finally {
    sqlSession.close();
  }
}
 
Example 18
Source File: MybatisSelectTest.java    From code with Apache License 2.0 5 votes vote down vote up
@Before//在测试方法执行之前执行
public void init() throws Exception {
    //1.读取配置文件
    in = Resources.getResourceAsStream("SqlMapConfig.xml");
    //2.创建构建者对象
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    //3.创建 SqlSession 工厂对象
    SqlSessionFactory factory = builder.build(in);
    //4.创建 SqlSession 对象
    session = factory.openSession();
    //5.创建 Dao 的代理对象
    userMapper = session.getMapper(UserMapper.class);
}
 
Example 19
Source File: DefaultResultHandlerTypeTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test
public void testSelectList() throws Exception {
  String xmlConfig = "org/apache/ibatis/submitted/result_handler_type/MapperConfig.xml";
  SqlSessionFactory sqlSessionFactory = getSqlSessionFactoryXmlConfig(xmlConfig);
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    List<Person> list = sqlSession
        .selectList("org.apache.ibatis.submitted.result_handler_type.PersonMapper.doSelect");
    assertEquals(list.size(), 2);
    assertEquals("java.util.LinkedList", list.getClass().getCanonicalName());
  } finally {
    sqlSession.close();
  }
}
 
Example 20
Source File: CmsTest.java    From oneops with Apache License 2.0 4 votes vote down vote up
/**
 * @param args
 * @throws IOException 
 * @throws SQLException 
 */
public static void _main(String[] args) throws IOException, SQLException {
	String resource = "mybatis-config.xml";
	Reader reader = Resources.getResourceAsReader(resource);
	SqlSessionFactory sqlsf = new SqlSessionFactoryBuilder().build(reader);

	SqlSession session = sqlsf.openSession();
	CIMapper ciMapper = session.getMapper(CIMapper.class);
	ClazzMapper clMapper = session.getMapper(ClazzMapper.class);
	NSMapper nsMapper = session.getMapper(NSMapper.class);
	RelationMapper rlMapper = session.getMapper(RelationMapper.class);
	CmsCmProcessor cmProcessor = new CmsCmProcessor();
	
	cmProcessor.setCiMapper(ciMapper);
	cmProcessor.setCmValidator(cmValidator);
	cmProcessor.setCmsNsProcessor(nsMan);
	
	cmValidator.setCmsMdProcessor(mdMan);
	cmValidator.setCmsNsProcessor(nsMan);
	
	nsMan.setNsMapper(nsMapper);
	
	CmsMdProcessor mdProcessor = new CmsMdProcessor();
	mdProcessor.setClazzMapper(clMapper);
	mdProcessor.setRelationMapper(rlMapper);
	
	
	
	try {
		testQueryAttrs(ciMapper);
		//testState(sqlsf);
		//testClazzes(sqlsf);
		//testCreateOrg();
		//testCreateAssembly();
		//testCreatPlatform(sqlsf);
		//int newRelId = testCreateRelation(sqlsf, 1048, 1052);
		//testGetRelation(sqlsf, newRelId);
		//testGetToFromRelation(sqlsf, 1048);
		//testUpdateCI(sqlsf);
		//testDeleteCi(sqlsf);
		//testGetCiById(sqlsf);
		//testGetCi(sqlsf);
		//testCreateClazz(sqlsf);
		//testGetClazz(sqlsf);
		session.commit();
	} finally {
		session.close();
	}
}