728x90
application.properties 설정
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/test1
spring.datasource.primary.username=root
spring.datasource.primary.password=123456
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/test2
spring.datasource.secondary.username=root
spring.datasource.secondary.password=123456
spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver
 

또는 application.yaml 설정

spring:
    datasource:
        primary:
            driver-class-name: com.mysql.cj.jdbc.Driver
            jdbc-url: jdbc:mysql://localhost:3306/test1
            password: root
            username: root
        secondary:
            driver-class-name: com.mysql.cj.jdbc.Driver
            jdbc-url: jdbc:mysql://localhost:3306/test2
            password: root
            username: root
단일 datasource 설정과 다르게 다중 datasource 는 spring.datasource 뒤에 접두사 primary 와 secondary 로 구분하고 datasource 를 초기화 할때 사용하게 된다. Springboot 2.x 은 spring.datasource.secondary.jdbc-url 를 사용하고 Springboot 1.x 은 spring.datasource.secondary.url 를 사용하한다. 실행시 java.lang.IllegalArgumentException:jdbcUrl is required with driverClassName 발생하면 해당 버전별 설정이 제대로 되었는지 확인해보면 된다.
 
DataSource 초기화 및 JdbcTemplate 설정
@Configuration
public class DataSourceConfiguration {

    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource primaryDataSource) {
        return new JdbcTemplate(primaryDataSource);
    }

    @Bean
    public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
        return new JdbcTemplate(secondaryDataSource);
    }

}

테스트 코드 작성

@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter37ApplicationTests {

    @Autowired
    protected JdbcTemplate primaryJdbcTemplate;

    @Autowired
    protected JdbcTemplate secondaryJdbcTemplate;

    @Before
    public void setUp() {
        primaryJdbcTemplate.update("DELETE  FROM  USER ");
        secondaryJdbcTemplate.update("DELETE  FROM  USER ");
    }

    @Test
    public void test() throws Exception {

        primaryJdbcTemplate.update("insert into user(name,age) values(?, ?)", "aaa", 20);
        primaryJdbcTemplate.update("insert into user(name,age) values(?, ?)", "bbb", 30);

        secondaryJdbcTemplate.update("insert into user(name,age) values(?, ?)", "ccc", 20);

        Assert.assertEquals("2", primaryJdbcTemplate.queryForObject("select count(1) from user", String.class));

        Assert.assertEquals("1", secondaryJdbcTemplate.queryForObject("select count(1) from user", String.class));
    }

}

'Springboot2.x 강좌 > DB연결' 카테고리의 다른 글

MyBatis 의 다중 DataSource  (0) 2023.01.05
Spring Data JPA 다중 DataSource  (0) 2023.01.05
XML 로 Mybatis 설정하기  (0) 2023.01.05
Mybatis 로 Mysql 연결하기  (0) 2023.01.05
Spring Data JPA  (0) 2023.01.05
728x90

main class 작성

@MapperScan("com.blake.demo.mapper")
@SpringBootApplication
public class XmlMaybatisApplication {

	public static void main(String[] args) {
		SpringApplication.run(XmlMaybatisApplication.class, args);
	}

}

Mapper interface 작성

public interface UserMapper {

    User findByName(@Param("name") String name);

    int insert(@Param("name") String name, @Param("age") Integer age);

}

.properties 혹은 .yml 파일에 설정 추가

mybatis.mapper-locations=classpath:mapper/*.xml

테스트 코드 작성

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.blake.demo.mapper.UserMapper">
    <select id="findByName" resultType="com.blake.demo.entity.User">
        SELECT * FROM USER WHERE NAME = #{name}
    </select>

    <insert id="insert">
        INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})
    </insert>
</mapper>

끝!

'Springboot2.x 강좌 > DB연결' 카테고리의 다른 글

Spring Data JPA 다중 DataSource  (0) 2023.01.05
JdbcTemplate 다중 DataSource  (0) 2023.01.05
Mybatis 로 Mysql 연결하기  (0) 2023.01.05
Spring Data JPA  (0) 2023.01.05
Druid datasource 연결  (0) 2023.01.05
728x90

pom.xml

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

mybatis-spring-boot-starter

  • 2.1.x vesrion : MyBatis 3.5+、Java 8+、Spring Boot 2.1+
  • 2.0.x vesrion : MyBatis 3.5+、Java 8+、Spring Boot 2.0/2.1
  • 1.3.x vesrion : MyBatis 3.4+、Java 6+、Spring Boot 1.5

현재까지 2.1.x 과 1.3.x 을 많이 사용한다.

application.properties 설정

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

application.yml

spring:
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        password: ''
        url: jdbc:mysql://localhost:3306/test
        username: root

테이블 생성.sql

CREATE TABLE `User` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `name` varchar(100) COLLATE utf8mb4_general_ci DEFAULT NULL,
  `age` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci

User 도메인 생성

@Data
@NoArgsConstructor
public class User {

    private Long id;

    private String name;
    private Integer age;

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

Mapper interface 작성

@Mapper
public interface UserMapper {

    @Select("SELECT * FROM USER WHERE NAME = #{name}")
    User findByName(@Param("name") String name);

    @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);

}
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisDemoApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    @Rollback
    public void test() throws Exception {
        userMapper.insert("AAA", 20);
        User u = userMapper.findByName("AAA");
        Assert.assertEquals(20, u.getAge().intValue());
    }

}

@Param

@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);

Map

@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})")
int insertByMap(Map<String, Object> map);

Object

@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
int insertByUser(User user);

C,R,U,D mapper interface 작성

public interface UserMapper {

    @Select("SELECT * FROM user WHERE name = #{name}")
    User findByName(@Param("name") String name);

    @Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);

    @Update("UPDATE user SET age=#{age} WHERE name=#{name}")
    void update(User user);

    @Delete("DELETE FROM user WHERE id =#{id}")
    void delete(Long id);
}

테스트 코드 작성

@Transactional
@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisDemoApplicationTests {

	@Autowired
	private UserMapper userMapper;

	@Test
	@Rollback
	public void testUserMapper() throws Exception {
		// insert 후 select 하여 검증
		userMapper.insert("AAA", 20);
		User u = userMapper.findByName("AAA");
		Assert.assertEquals(20, u.getAge().intValue());
		// update 후 select 하여 검증
		u.setAge(30);
		userMapper.update(u);
		u = userMapper.findByName("AAA");
		Assert.assertEquals(30, u.getAge().intValue());
		// 데이터 삭제 및 select 검증
		userMapper.delete(u.getId());
		u = userMapper.findByName("AAA");
		Assert.assertEquals(null, u);
	}
}

Result 객체 바인딩

@Results({
    @Result(property = "name", column = "name"),
    @Result(property = "age", column = "age")
})
@Select("SELECT name, age FROM user")
List<User> findAll();

테스트 코드 작성

@Test
@Rollback
public void testUserMapper() throws Exception {
	List<User> userList = userMapper.findAll();
	for(User user : userList) {
		Assert.assertEquals(null, user.getId());
		Assert.assertNotEquals(null, user.getName());
	}
}

 

'Springboot2.x 강좌 > DB연결' 카테고리의 다른 글

JdbcTemplate 다중 DataSource  (0) 2023.01.05
XML 로 Mybatis 설정하기  (0) 2023.01.05
Spring Data JPA  (0) 2023.01.05
Druid datasource 연결  (0) 2023.01.05
Hikari 설정  (0) 2023.01.04
728x90

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

application.propertise

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop

혹은 application.yml

spring:
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        password: ''
        url: jdbc:mysql://localhost:3306/test
        username: root
    jpa:
        properties:
            hibernate:
                hbm2ddl:
                    auto: create-drop

User 도메인 작성

@Entity
@Data
@NoArgsConstructor
public class User {

    @Id
    @GeneratedValue
    private Long id;

    private String name;
    private Integer age;

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

Repository interface 작성

public interface UserRepository extends JpaRepository<User, Long> {

    User findByName(String name);

    User findByNameAndAge(String name, Integer age);

    @Query("from User u where u.name=:name")
    User findUser(@Param("name") String name);

}

테스트 코드 작성

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void test() throws Exception {

        // 데이터 10건 생성
        userRepository.save(new User("AAA", 10));
        userRepository.save(new User("BBB", 20));
        userRepository.save(new User("CCC", 30));
        userRepository.save(new User("DDD", 40));
        userRepository.save(new User("EEE", 50));
        userRepository.save(new User("FFF", 60));
        userRepository.save(new User("GGG", 70));
        userRepository.save(new User("HHH", 80));
        userRepository.save(new User("III", 90));
        userRepository.save(new User("JJJ", 100));

        // findAll, 전체조회
        Assert.assertEquals(10, userRepository.findAll().size());

        // findByName, 이름이 FFF인 사용자 User
        Assert.assertEquals(60, userRepository.findByName("FFF").getAge().longValue());

        // findUser, 이름이 FFF인 사용자 User
        Assert.assertEquals(60, userRepository.findUser("FFF").getAge().longValue());

        // findByNameAndAge, 이름이 FFF인 , 나이는 60인 사용자 User
        Assert.assertEquals("FFF", userRepository.findByNameAndAge("FFF", 60).getName());

        // 이름 AAA인 User 삭제
        userRepository.delete(userRepository.findByName("AAA"));

        // findAll, 전체조회하여 정상 삭제 되었는지 확인
        Assert.assertEquals(9, userRepository.findAll().size());

    }
}

끝!

'Springboot2.x 강좌 > DB연결' 카테고리의 다른 글

XML 로 Mybatis 설정하기  (0) 2023.01.05
Mybatis 로 Mysql 연결하기  (0) 2023.01.05
Druid datasource 연결  (0) 2023.01.05
Hikari 설정  (0) 2023.01.04
JdbcTemplate 로 db 접근해보자  (0) 2023.01.04

+ Recent posts