1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.submitted.postgres_genkeys;
17
18 import static org.junit.jupiter.api.Assertions.assertEquals;
19
20 import org.apache.ibatis.BaseDataTest;
21 import org.apache.ibatis.mapping.Environment;
22 import org.apache.ibatis.session.Configuration;
23 import org.apache.ibatis.session.SqlSession;
24 import org.apache.ibatis.session.SqlSessionFactory;
25 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
26 import org.apache.ibatis.testcontainers.PgContainer;
27 import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
28 import org.junit.jupiter.api.BeforeAll;
29 import org.junit.jupiter.api.Tag;
30 import org.junit.jupiter.api.Test;
31
32 @Tag("TestcontainersTests")
33 class PostgresGeneratedKeysTest {
34
35 private static SqlSessionFactory sqlSessionFactory;
36
37 @BeforeAll
38 static void setUp() throws Exception {
39 Configuration configuration = new Configuration();
40 Environment environment = new Environment("development", new JdbcTransactionFactory(),
41 PgContainer.getUnpooledDataSource());
42 configuration.setEnvironment(environment);
43 configuration.setUseGeneratedKeys(true);
44 configuration.addMapper(Mapper.class);
45 sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
46
47 BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(),
48 "org/apache/ibatis/submitted/postgres_genkeys/CreateDB.sql");
49 }
50
51 @Test
52 void testInsertIntoTableWithNoSerialColumn() {
53 try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
54 Mapper mapper = sqlSession.getMapper(Mapper.class);
55 Section section = new Section();
56 section.setSectionId(2);
57 section.setName("Section 2");
58 int result = mapper.insertSection(section);
59 assertEquals(1, result);
60 }
61 }
62
63 @Test
64 void testUpdateTableWithSerial() {
65 try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
66 Mapper mapper = sqlSession.getMapper(Mapper.class);
67 User user = new User();
68 user.setUserId(1);
69 user.setName("Ethan");
70 int result = mapper.updateUser(user);
71 assertEquals(1, result);
72 }
73 }
74
75 @Test
76 void testUnusedGeneratedKey() {
77 try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
78 Mapper mapper = sqlSession.getMapper(Mapper.class);
79 int result = mapper.insertUser("John");
80 assertEquals(1, result);
81 }
82 }
83 }