springboot 整合 mybatis

啓動類

//mybatis會掃描的包
@MapperScan(basePackages = "com.example")
@SpringBootApplication(scanBasePackages = "com.example")
public class Application {

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

}

application.properties

server.port=8081
server.context-path=/springboot
#debug設爲true,將在控制檯打印當前項目已啓用和未啓用的自動配置報告
#debug=true
#指定使用的配置文件
spring.profiles.active=dev
#spring.profiles.active=test
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/qinwei?useUnicode=true&characterEncoding=utf-8
#替換默認的數據庫連接池
spring.datasource.type= com.alibaba.druid.pool.DruidDataSource
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driverClassName = com.mysql.jdbc.Driver
# 下面爲連接池的補充設置,應用到上面所有數據源中
# 初始化時建立物理連接的個數。
spring.datasource.initialSize=5
# 最小連接的個數。
spring.datasource.minIdle=5
# 最大連接的個數。
spring.datasource.maxActive=10

DruidConfiguration.java

@Configuration
@EnableTransactionManagement // 啓註解事務管理,等同於xml配置方式的 <tx:annotation-driven />
public class DruidConfiguration implements TransactionManagementConfigurer {

    @Value("${spring.datasource.driverClassName}")
    private String driver;

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.initialSize}")
    private int initialSize;

    @Value("${spring.datasource.minIdle}")
    private int minIdle;

    @Value("${spring.datasource.maxActive}")
    private int maxActive;

    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),
                "/druid/*");
        // 添加初始化參數:initParams
        // 白名單:
        // servletRegistrationBean.addInitParameter("allow","127.0.0.1");
        // IP黑名單 (存在共同時,deny優先於allow) : 如果滿足deny的話提示:Sorry, you are not
        // permitted to view this page.
        // servletRegistrationBean.addInitParameter("deny","ip");
        // 登錄查看信息的賬號密碼.
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "123456");
        // 是否能夠重置數據.
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    /**
     * 配置過濾器
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        // 過濾地址
        filterRegistrationBean.addUrlPatterns("/*");
        // 不需要參與過濾的地址或者文件
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

    @Bean
    public DataSource druidDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        druidDataSource.setInitialSize(initialSize);
        druidDataSource.setMinIdle(minIdle);
        druidDataSource.setMaxActive(maxActive);

        try {
            druidDataSource.setFilters("stat,wall");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return druidDataSource;
    }

    @Bean(name = "txManage")
    public PlatformTransactionManager txManager() {
        return new DataSourceTransactionManager(druidDataSource());
    }

    // 實現接口 TransactionManagementConfigurer 方法,其返回值代表在擁有多個事務管理器的情況下默認使用的事務管理器
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return txManager();
    }

}

TestMapper

@Mapper
public interface TestMapper {

    @Select("SELECT * FROM CITY WHERE state = #{state}")
    City findByState(@Param("state") String state);

    @Update("update city set name=#{city.name},state=#{city.state} where id=#{city.id}")
    void upadate(@Param("city") City city);

    @Delete("delete from city where id = #{id}")
    void deleteId(@Param("id") int id);

    @Insert("insert into city(name, state, country) values(#{city.name}, #{city.state}, #{city.country})")
    @Options(useGeneratedKeys = true, keyProperty = "city.id")
    int insert(@Param("city") City city);

    @Select("SELECT * FROM city WHERE id = #{0}")
    City findById(int id);

    /**
     * 級聯查詢,一對一,返回自定義對象
     */
    @Select("select * from school where id=#{id}")
    @Results(id = "school", value = { @Result(column = "id", property = "id"),
            @Result(column = "name", property = "name"), @Result(column = "state", property = "state"),
            @Result(column = "cityId", property = "cityId"),
            @Result(column = "cityId", property = "city", one = @One(select = "com.example.mybatis.TestMapper.findById")) })
    School findOneToOne(@Param("id") int id);

    @Select(" select * from school where cityId=#{cityId} ")
    School findManyToOne(@Param("cityId") int id);

    @Select(" select * from  city where id=#{id} ")
    @Results(id = "city", value = { @Result(column = "id", property = "id", id = true),
            @Result(column = "name", property = "name"), @Result(column = "state", property = "state"),
            @Result(column = "country", property = "country"),
            @Result(column = "id", property = "schools", many = @Many(select = "com.example.mybatis.TestMapper.findManyToOne")) })
    City findOneToMany(@Param("id") int id);
}

City .java

public class City {
    private Integer id;

    private String name;

    private String state;

    private String country;

    private List<School> schools;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public List<School> getSchools() {
        return schools;
    }

    public void setSchools(List<School> schools) {
        this.schools = schools;
    }

}

School.java

public class School {
    private Integer id;

    private String name;

    private String state;

    private String cityId;

    private City city;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getCityId() {
        return cityId;
    }

    public void setCityId(String cityId) {
        this.cityId = cityId;
    }

    public City getCity() {
        return city;
    }

    public void setCity(City city) {
        this.city = city;
    }

}
@RestController
public class MybatisTest {
    private static final Logger LOGGER = LoggerFactory.getLogger(MybatisTest.class);

    @Autowired
    private TestMapper mapper;

    private Gson gson = new Gson();

    // 在存在多個事務管理器的情況下,如果使用value具體指定
    // 則默認使用方法 annotationDrivenTransactionManager() 返回的事務管理器
    @RequestMapping("mybatis")
    @Transactional(value = "txManage")
    public void mybatisMethod() {
        City c1 = mapper.findById(6);
        LOGGER.info(gson.toJson(c1));

        City city = mapper.findByState("OFF");
        LOGGER.info(gson.toJson(city));

        School school = mapper.findOneToOne(1);
        LOGGER.info(gson.toJson(school));

        city = mapper.findOneToMany(1);
        LOGGER.info(gson.toJson(city));

        City c = new City();
        c.setId(5);
        c.setName("廣東");
        c.setState("ON");
        c.setCountry("CN");
        LOGGER.info("insert result: " + mapper.insert(c));
//      throw new RuntimeException("just a test");
    }
}
CREATE TABLE `city` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) DEFAULT NULL,
  `state` varchar(32) DEFAULT NULL,
  `country` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8;

CREATE TABLE `school` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) DEFAULT NULL,
  `state` varchar(32) DEFAULT NULL,
  `cityId` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

發佈了36 篇原創文章 · 獲贊 12 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章