spring 통합 my batis (순 주해)

44966 단어 Javaspringmybatis
  • 도입 의존
    <properties>
      
      <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
      <maven.compiler.source>1.8maven.compiler.source>
      <maven.compiler.target>1.8maven.compiler.target>
    
      
      <spring.version>5.2.0.RELEASEspring.version>
      <juint.version>4.12juint.version>
      <aspectjweaver.version>1.9.2aspectjweaver.version>
      <aspectjrt.version>1.9.2aspectjrt.version>
    
        
        <mybatis.version>3.4.6mybatis.version>
        <mybatis.spring.version>1.3.2mybatis.spring.version>
        <HikariCP.version>3.3.1HikariCP.version>
      <mysql.connector.java.version>5.1.38mysql.connector.java.version>
    
      
      <lombok.version>1.18.12lombok.version>
      <logback.classic.version>1.2.3logback.classic.version>
    properties>
    
    <dependencies>
      
      <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-contextartifactId>
        <version>${spring.version}version>
      dependency>
      <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-txartifactId>
        <version>${spring.version}version>
        <exclusions>
          <exclusion>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-beansartifactId>
          exclusion>
          <exclusion>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
          exclusion>
        exclusions>
      dependency>
      <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-aspectsartifactId>
        <version>${spring.version}version>
      dependency>
      <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-jdbcartifactId>
        <version>${spring.version}version>
      dependency>
      <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-testartifactId>
        <version>${spring.version}version>
      dependency>
      <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>${juint.version}version>
      dependency>
      
      <dependency>
        <groupId>org.aspectjgroupId>
        <artifactId>aspectjweaverartifactId>
        <version>${aspectjweaver.version}version>
      dependency>
      <dependency>
        <groupId>org.aspectjgroupId>
        <artifactId>aspectjrtartifactId>
        <version>${aspectjrt.version}version>
      dependency>
    
      
      <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>${mybatis.version}version>
      dependency>
      <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatis-springartifactId>
        <version>${mybatis.spring.version}version>
      dependency>
      <dependency>
        <groupId>com.zaxxergroupId>
        <artifactId>HikariCPartifactId>
        <version>${HikariCP.version}version>
      dependency>
      <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>${mysql.connector.java.version}version>
      dependency>
    
      
      <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
        <version>${lombok.version}version>
      dependency>
      <dependency>
        <groupId>ch.qos.logbackgroupId>
        <artifactId>logback-classicartifactId>
        <version>${logback.classic.version}version>
      dependency>
    
    dependencies>
    
  • jdbc 프로필 과 로그 파일 가 져 오기
  • jdbc.properties
    jdbc.driverClassName=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql:///db1
    jdbc.username=root
    jdbc.password=root
    
  • logback.xml
    
    
    <configuration>
        
        <statusListener class="ch.qos.logback.core.status.NopStatusListener" />
        
        <property name="CONSOLE_LOG_PATTERN"
                  value="  :%date{yyyy-MM-dd HH:mm:ss}   : %highlight(%-5level)   : %boldYellow(%thread)  : %boldGreen(%logger)   : %msg%n"/>
        
        <property name="ERRINFOFILE_LOG_PATTERN" value="  :%date{yyyy-MM-dd HH:mm:ss}   : %-5level   : %thread  : %logger   : %msg%n"/>
    
        <appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender">
            <layout class="ch.qos.logback.classic.PatternLayout">
                <pattern>
                    ${CONSOLE_LOG_PATTERN}
                pattern>
            layout>
        appender>
    
        <root level="info">
            <appender-ref ref="consoleLog" />
        root>
    
    configuration>
    

  • 레이 어 링 코드
  • bean
    @Data
    public class User implements Serializable {
             
        private Integer id;
        private String name;
        private Integer age;
        private String address;
    }
    
  • mapper
    public interface UserMapper {
             
        List<User> findAll();
    }
    
  • mapper 맵 파일
    
    
    <mapper namespace="com.ujiuye.mapper.UserMapper">
        <select id="findAll" resultType="com.ujiuye.bean.User">
            select * from t_user;
        select>
    mapper>
    
  • service
    public interface IUserService {
             
        List<User> getAllUser();
    }
    
    @Service
    public class UserServiceImpl implements IUserService {
             
        @Autowired
        private UserMapper userMapper;
    
        @Override
        public List<User> getAllUser() {
             
            return userMapper.findAll();
        }
    }
    

  • spring 설정 클래스 작성
    @Configuration
    @PropertySource("classpath:jdbc.properties")
    @MapperScan(basePackages = "com.ujiuye.mapper")//mapper    
    @ComponentScan("com.ujiuye") //    
    public class BeanConfig {
           
        @Value("${jdbc.driverClassName}")
        private String driverClassName;
        @Value("${jdbc.url}")
        private String jdbcUrl;
        @Value("${jdbc.username}")
        private String username;
        @Value("${jdbc.password}")
        private String password;
    
        //     
        @Bean
        public HikariDataSource hikariDataSource(){
           
            HikariDataSource dataSource = new HikariDataSource();
            dataSource.setDriverClassName(driverClassName);
            dataSource.setJdbcUrl(jdbcUrl);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            return dataSource;
        }
    
        //sqlsessionFactory  
        @Bean
        public SqlSessionFactoryBean sqlSessionFactoryBean(){
           
            SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
            factoryBean.setDataSource(hikariDataSource());
            factoryBean.setMapperLocations(new Resource[]{
           new ClassPathResource("mappers/UserMapper.xml")});
            factoryBean.setTypeAliasesPackage("com.ujiuye.bean");
            return factoryBean;
        }
    }
    
  • 테스트
    @Slf4j
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = {
           BeanConfig.class})
    public class AnnoAppTest {
           
    
        @Autowired
        private IUserService userService;
    
        @Test
        public void testGetAllUser() throws Exception{
           
            List<User> list = userService.getAllUser();
            for (User user : list) {
           
                log.info("{}",user);
            }
        }
    }
    
  • 좋은 웹페이지 즐겨찾기