1.java的maven依赖包
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.3.6.RELEASE</spring.version>
<springboot.version>1.5.1.RELEASE</springboot.version>
</properties>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.26</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${springboot.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
2. main主函数(启动spring)
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class App
{ public static void main( String[] args )
{
SpringApplication.run(App.class,args);
}
}
3.建立业务处理类
1)第1种方法 使用自动装载(@Autowired)
package com.cnblog.g2; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component; @Component
public class CommandStart implements CommandLineRunner{ @Autowired
public UserService userService;
@Override
public void run(String... strings) throws Exception { if(userService!=null)
{ this.userService.insertUsers(new Users("YangT", "123sd")); } } }
2)第2种方法,使用 Context.getBean
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component; @Component
public class CommandStart implements CommandLineRunner,ApplicationContextAware {
ApplicationContext applicationContext; public UserService userService;
@Override
public void run(String... strings) throws Exception {
//这里的bean名称,首字母要小写
Object userService = applicationContext.getBean("userServiceImpl");
if(userService!=null)
{
this.userService = (UserService)userService;
if(this.userService != null) {
this.userService.insertUsers(new Users("YangT", "123sd"));
}
} } @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
4.业务实现类
public interface UserService {
public List<Users> queryUsers();
public int insertUsers(Users user);
} @Component
public class UserServiceImpl implements UserService{
@Autowired
private UsersMapper usersMapper; @Override
public List<Users> queryUsers(){
return usersMapper.queryUsers();
} @Override
public int insertUsers(Users user){
return usersMapper.insertUsers(user);
}
}
5.SqlMapper相关
UsersMapper 在 com.cnblog.g2.mapper.UsersMapper里
@Repository
public interface UsersMapper {
public List<Users> queryUsers();
public Users queryUsersById(int id);
public int insertUsers(Users user);
public int updateUsers(Users user);
public int deleteUsers(int id);
}
<mapper namespace="com.cnblog.g2.mapper.UsersMapper"> <!-- 查询全部用户 -->
<select id="queryUsers" resultType="com.ppmoney.g2.Users">
select *
from tb_users
</select>
<!-- 按照ID查询 -->
<select id="queryUsersById" parameterType="int" resultType="com.ppmoney.g2.Users">
select * from tb_users where id=#{id}
</select>
<!-- 添加用户 -->
<insert id="insertUsers" parameterType="com.ppmoney.g2.Users" >
insert into tb_users(username,password)
values(#{userName},#{password}) <selectKey keyProperty="id" resultType="int" order="AFTER">
select @@identity
</selectKey>
</insert>
<!-- 修改用户 -->
<update id="updateUsers" parameterType="com.ppmoney.g2.Users">
update tb_users
set password=#{password}
where id=#{id}
</update>
<!-- 删除用户 -->
<delete id="deleteUsers" parameterType="int">
delete
from tb_users
where id=#{id}
</delete>
</mapper>
6. sql配置相关.
jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc\:sqlserver\://192.168.1.10\:1433;DatabaseName=pt
jdbc.username=dev
jdbc.password=dev
jdbc.poolMaximumActiveConnections=30 jdbc.minIdle=10
jdbc.maxWait=3000
package com.cnblog.g2; import com.alibaba.druid.pool.DruidDataSource; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource; @Configuration
@MapperScan(basePackages = {"com.cnblog.g2.mapper"})
public class MybatisConfiguration { private static Log logger = LogFactory.getLog(MybatisConfiguration.class); @Autowired
private Environment env; @Bean
public DataSource dataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setPassword(env.getProperty("jdbc.password"));
druidDataSource.setUsername(env.getProperty("jdbc.username"));
druidDataSource.setUrl(env.getProperty("jdbc.url"));
druidDataSource.setDriverClassName(env.getProperty("jdbc.driver"));
druidDataSource.setMaxActive(env.getProperty("jdbc.poolMaximumActiveConnections",Integer.class));
druidDataSource.setMinIdle(env.getProperty("jdbc.minIdle", Integer.class));
druidDataSource.setMaxWait(env.getProperty("jdbc.maxWait", Integer.class));
druidDataSource.setValidationQuery("Select 1");
return druidDataSource;
} @Bean
public SqlSessionFactory sqlSessionFactory(DataSource pooledDataSource) {
try {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(pooledDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mapping/*.xml")); return sessionFactory.getObject();
} catch (Exception e) {
logger.error("not install sessionFactory", e);
throw new RuntimeException("not install sessionFactory");
}
} @Bean
public DataSourceTransactionManager transaction(DataSource pooledDataSource) {
return new DataSourceTransactionManager(pooledDataSource);
}
}
或者可以直接在main里调用
@SpringBootApplication
public class App //implements ApplicationContextAware
{ public static void main( String[] args )
{
ApplicationContext applicationContext= SpringApplication.run(App.class,args); Object userService = applicationContext.getBean("userServiceImpl"); ((UserService)userService).insertUsers(new Users("YangT1", "123sd"));
}
}