刚从python转Java,马上就开始写spring boot了,再写的时候遇到了很多问题,记一下。
首先是连接数据库的工具,我一开始学的时候是用的jdbc或hibernate,但我的项目的需求是这样的:
数据库的表已经有了,而且来自于两个不同的数据库,我只要老老实实取出来返回给前端就好了。
考虑到jdbc大家用的少,而hibernate选择update模式可能你一个字段没配上就gg了,呃,然后想到Mybatis有mybatis generator代码生成工具,而且字段可以选自己需要的写上就可以了,所以最后用的Mybatis。
biuld.gradle文件很简单我就不贴了,网上都有。
首先是多数据源,application.properties是这样的:
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.ncuhomeblog.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.ncuhomeblog.url=jdbc:mysql://127.0.0.1:3306/ncuhomeblog?useSSL=false
spring.datasource.ncuhomeblog.username=root
spring.datasource.ncuhomeblog.password=123456
spring.datasource.ncuhomediary.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.ncuhomediary.url=jdbc:mysql://127.0.0.1:3306/ncuhomedairy?useSSL=false
spring.datasource.ncuhomediary.username=root
spring.datasource.ncuhomediary.password=123456
这里先定义了两个数据源,然后在config文件里:
@Configuration
@ConfigurationProperties("spring.datasource.ncuhomediary")
@MapperScan(basePackages = "cn.ncuhomer.mapper.ncuhomediary", sqlSessionFactoryRef = "ncuhomediarySessionFactory")
public class NcuhomeDiaryDatasSourceConfig {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
@NotNull
private String username;
@NotNull
private String password;
@NotNull
private String url;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Bean
public DataSource ncuhomeDairyDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
@Bean(name = "ncuhomediarySessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
//Can no longer use application.properties for mybatis configuration settings, so this is a hack for
//application.properties: mybatis.configuration.map-underscore-to-camel-case=true
org.apache.ibatis.session.Configuration ibatisConfiguration = new org.apache.ibatis.session.Configuration();
ibatisConfiguration.setMapUnderscoreToCamelCase(true);
sqlSessionFactoryBean.setConfiguration(ibatisConfiguration);
sqlSessionFactoryBean.setDataSource(ncuhomeDairyDataSource());
return sqlSessionFactoryBean.getObject();
}
}
这里的@ConfigurationProperties("spring.datasource.ncuhomediary")是自动把属性文件的属性赋值给这个类的属性,一个一个@Value效果也是一样的。
另一个config也类似,只是不需要bean的名字以及sqlSessionFactoryRef,然后把mapperscan的扫描的地方换一下,两个方法上加@Primary就可以了。
加了@Primary就是告诉程序这是主数据库,先搞这,不是主数据库的得让程序知道mapper文件所对应的数据源是啥,所以Bean要带个名字,不然它就默认是主数据源了。
mapper文件在连表查询的时候一起讲。
mybatis其实完全可以用注释代替xml的。这里的需求是,posts这张表,只存了作者的id(created_by),我必须去users里根据id把作者的名字取出来,下面先给代码:
@Mapper
public interface NcuhomeBlogMapper {
@Select("select * from posts where status='published' and visibility='public' order by updated_at desc limit 4")
@Results({
@Result(property = "title", column = "title"),
@Result(property = "url", column = "slug"),
@Result(property = "cover", column = "html"),
@Result(property = "time", column = "updated_at"),
@Result(property = "author", column = "created_by", one = @One(select = "cn.ncuhomer.mapper.ncuhomebloguser.NcuhomeBlogUserMapper.findById"))
})
public List<NcuhomeBlog> selectByCondition();
}
@Mapper
public interface NcuhomeBlogUserMapper {
@Select("select * from users where id=#{id}")
@Results({
@Result(property = "name", column = "name")
})
public NcuhomeBlogUser findById(@Param(value = "id") Integer id);
}
就是@one的简单运用,这里要注意@one的那一行的@property,它的author属性的类型是一个author实体类。
这里再解释一下,这里连表查询,就是上面那个先把很多东西select出来,然后column再把craeted_by字段挑出来,传到@0ne对应的那个映射接口,它接收一个id,然后根据id查,最后把name字段筛选出来给上面那个映射接口的author属性,完成了连接查询。