Springboot入门之数据访问层

一、Springboot整合使用jdbcTemplete

1.pom文件引入


        org.springframework.boot
        spring-boot-starter-parent
        1.5.2.RELEASE
    
    
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
            mysql
            mysql-connector-java
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.boot
            spring-boot-starter-web
        
    

2.配置application.properties(我的数据库没密码,你的加上就行)

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
#spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

3.编写一个service接口和实现类

public interface UserService {
    public void insertJdbcUser();
}
@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void insertJdbcUser() {
        jdbcTemplate.update("insert into user values(null,?,?);","lisi",19);
    }
}

4.编写一个controller及启动类

@RestController
public class IndexController {
    @Autowired
    private UserService userService;

    @RequestMapping("/index")
    public String index(){
        userService.insertJdbcUser();
        return "success";
    }
}
@ComponentScan(basePackages = { "cn.iponkan.controller", "cn.iponkan.service" })
@EnableAutoConfiguration
public class SpringBootApplication {
    public static void main(String[] args){
        SpringApplication.run(SpringBootApplication.class,args);
    }
}

二、Springboot整合使用mybatis

1.pom文件引入


        org.springframework.boot
        spring-boot-starter-parent
        1.5.2.RELEASE
    
    
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-tomcat
        
        
            org.apache.tomcat.embed
            tomcat-embed-jasper
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.1.1
        
        
            mysql
            mysql-connector-java
        
    

2.配置application.properties(我的数据库没密码,你的加上就行)
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
#spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3.编写实体类及对应的Mapper代码

public class User {
    private Integer id;
    private String name;
    private Integer age;

    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 Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

public interface UserMapper
{
    @Select("select * from user where name =#{name}")
    User getName(@Param("name")String name);
}

4.编写Controller及启动类

@Controller
public class Indexcontroller {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @ResponseBody
    @RequestMapping("/getName")
    public User getName(String name){
        return userMapper.getName(name);
    }
}
@ComponentScan(basePackages = { "cn.iponkan.controller"})
@MapperScan(basePackages = {"cn.iponkan.mapper"})
@EnableAutoConfiguration
public class SpringBootApplication {
    public static void main(String[] args){
        SpringApplication.run(SpringBootApplication.class,args);
    }
}

三、Springboot整合使用jpa

1.pom文件引入


        org.springframework.boot
        spring-boot-starter-parent
        1.5.2.RELEASE
    
    
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            mysql
            mysql-connector-java
        
        
            org.springframework.boot
            spring-boot-starter-web
        
    

2.配置application.properties(我的数据库没密码,你的加上就行)

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
#spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

3.创建实体类和Dao

@Entity(name = "user")
public class User {
    @Id
    @GeneratedValue
    private Integer id;
    @Column
    private String name;
    @Column
    private Integer age;

    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 Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public interface UserRepository extends JpaRepository {
}

4.编写Controller及启动类

@RestController
public class IndexController {
    @Autowired
    private UserRepository userRepository;
    @RequestMapping("/index")
    public String index(Integer id){
       User u= userRepository.findOne(id);
       return u.toString();
    }
}
@ComponentScan(basePackages = { "cn.iponkan.controller" })
@EnableJpaRepositories(basePackages = {"cn.iponkan.repository"})
@EntityScan(basePackages = {"cn.iponkan.entity"})
@EnableAutoConfiguration
public class SpringbootApp {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootApp.class,args);
    }
}

四、Springboot整合多数据源

1.pom文件


        org.springframework.boot
        spring-boot-starter-parent
        1.5.2.RELEASE
    
    
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-tomcat
        
        
            org.apache.tomcat.embed
            tomcat-embed-jasper
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.1.1
        
        
            mysql
            mysql-connector-java
        
    

2.application.properties

spring.datasource.test1.driverClassName = com.mysql.jdbc.Driver
spring.datasource.test1.url = jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf-8
spring.datasource.test1.username = root
#spring.datasource.test1.password = root

spring.datasource.test2.driverClassName = com.mysql.jdbc.Driver
spring.datasource.test2.url = jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=utf-8
spring.datasource.test2.username = root
#spring.datasource.test2.password = root

3.新增两个数据源类

@Configuration// 注入到springboot容器中
@MapperScan(basePackages = "cn.iponkan.test01", sqlSessionFactoryRef = "test1SqlSessionFactory")
public class Datasource1 {

	@Bean(name = "test1DataSource")
	@ConfigurationProperties(prefix = "spring.datasource.test1")
	@Primary
	public DataSource testDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "test1SqlSessionFactory")
	@Primary
	public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		// bean.setMapperLocations(
		// new
		// PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));
		return bean.getObject();
	}

	@Bean(name = "test1TransactionManager")
	@Primary
	public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "test1SqlSessionTemplate")
	public SqlSessionTemplate testSqlSessionTemplate(
			@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

}
@Configuration
@MapperScan(basePackages="cn.iponkan.test02",sqlSessionFactoryRef="test2SqlSessionFactory")
public class Datasource2 {

	@Bean(name = "test2DataSource")
	@ConfigurationProperties(prefix = "spring.datasource.test2")
	public DataSource testDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "test2SqlSessionFactory")
	public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
//		bean.setMapperLocations(
//				new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test2/*.xml"));
		return bean.getObject();
	}
	
	@Bean(name = "test2TransactionManager")
	public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "test2SqlSessionTemplate")
	public SqlSessionTemplate testSqlSessionTemplate(
			@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}

4.分包创建实体类、Mapper和service

public class User {
    private Integer id;
    private String name;
    private Integer age;

    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 Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

@CacheConfig(cacheNames = "baseCache")
public interface User1Mapper {

	@Insert("insert into user values(null,#{name},#{age});")
	public int addUser(@Param("name") String name, @Param("age") Integer age);
}
@Service
public class User01Service {
	@Autowired
	private User1Mapper user1Mapper;

	public int addUser(String name, Integer age) {
		return user1Mapper.addUser(name, age);
	}

}

5.同第四步创建另一个包,注意相应的1改为2

6.写Controller类和启动类

@RestController
public class Indexcontroller {
    @Autowired
    private User1Mapper user1Mapper;
    @Autowired
    private User2Mapper user2Mapper;

    @RequestMapping("/add")
    public String add() {
        user1Mapper.addUser("Tung", 22);
        user2Mapper.addUser("Clare", 22);
        return "成功!";
    }
}
@ComponentScan(basePackages = { "cn.iponkan.controller","cn.iponkan.datasource","cn.iponkan.test01","cn.iponkan.test02"})
@EnableAutoConfiguration
public class SpringBootApplication {
    public static void main(String[] args){
        SpringApplication.run(SpringBootApplication.class,args);
    }
}

源代码见GitHub:https://github.com/tangqiangDong/Springboot点击打开链接

你可能感兴趣的:(SpringBoot)