已经用spring-boot启动一个新工程,能够运行,开始写业务代码。dao层繁杂的代码让人望而却步,急切找到一个方法来简化它。
网上找nutz在spring-boot中使用的相关资料,比较匮乏,自己边尝试边整理一下。官方demo
下面给出相关配置,Dao层一个业务实例,以及junit本地测试的实例。
maven
<dependency>
<groupId>org.nutz</groupId>
<artifactId>nutz-plugins-spring-boot-starter</artifactId>
<version>${version}</version>
</dependency>
gradle
compile group: 'org.nutz', name: 'nutz-plugins-spring-boot-starter', version: '1.r.63'
代码实例
1. 业务Dao接口(Resource是自定义的业务数据)
public interface ResourceDao {
void insertResource(Resource resource);
List<Resource> listResources();
}
2. 业务Dao实现
import org.nutz.dao.Cnd;
import org.nutz.dao.Condition;
import org.nutz.dao.Dao;
import org.nutz.dao.impl.NutDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class ResourceDaoImpl extends NutDao implements ResourceDao {
@Autowired
private Dao dao;
@Override
public void insertResource(Resource resource) {
dao.insert(resource);
}
@Override
public List<outfox.ynote.data.Resource> listResources() {
Condition condition = Cnd.orderBy().desc("id");
return dao.query(Resource.class, condition);
}
}
3. 配置文件
#---------jdbc with MySQL---------#
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/XXXX
spring.datasource.username=XXXX
spring.datasource.password=XXXX
4. 本地测试和数据库连接
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class TestResourceDao extends CommonTest{
@Autowired
public ResourceDao resourceDao;
@Test
public void test() {
Resource resource = new Resource();
// add some resource properties
resourceDao.insertResource(resource);
List<Resource> resourceList = resourceDao.listResources();
for (Resource temp : resourceList) {
System.out.println(temp.toString());
}
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class CommonTest {
@Autowired
@Qualifier("jdbcTemplate")
protected JdbcTemplate jdbcTemplate;
}
@Configuration
@EnableTransactionManagement
public class DBConfig {
@Bean(name = "jdbcTemplate")
public JdbcTemplate jdbcTemplate(
@Qualifier("dataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}