项目结构具体如下:
准备一个数据库:
架构是spring_db,表名为user_tb
结构如下:
第一步:配置pom文件(导入相应的坐标,注意spring-mybatis与mybatis的版本需要相对应,可以去官网查找对应的版本,也可以直接使用下面推荐的):
4.0.0 org.example spring-test2 1.0-SNAPSHOT 19 19 UTF-8 org.springframework spring-context 5.3.20 com.alibaba druid 1.1.24 org.mybatis mybatis 3.5.6 mysql mysql-connector-java 8.0.31 org.springframework spring-jdbc 6.0.6 org.mybatis mybatis-spring 1.3.0
第二步:
会有两种配置mybatis的方法,第一种使用配置文件,以下先演示第一种:
创建配置文件:
第二:编写properties文件(注意,不要少了冒号之类的符号,还有不要加引号当字符串):
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db
jdbc.username=root
jdbc.password=123456
第三,编写一个accountdao的接口,直接使用注解添加sql语句,这样可以省去在mybatis配置文件写的时间:
package com.wxy.dao;import com.wxy.domain.Account;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;import java.util.List;public interface AccountDao {@Insert("insert into tb_account(name,money)values (#{name},#{money})")void save(Account account);@Delete("delete from tb_account where id = #{id}")void delete(Integer id);@Update("update tb_account set name = #{name},money = ${money} where id = #{id}")void update(Account account);@Select("select * from tb_account where id = #{id}")Account findById(Integer id);}
第四,编写Accout类:
package com.wxy.domain;import java.io.Serializable;public class Account implements Serializable {private Integer id;private String name;private int money;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 int getMoney() {return money;}public void setMoney(int money) {this.money = money;}@Overridepublic String toString() {return "Account{" +"id=" + id +", name='" + name + '\'' +", money=" + money +'}';}
}
此时便可以直接编写测试类AppTest1:
package com.wxy;import com.wxy.dao.AccountDao;
import com.wxy.domain.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;
import java.io.InputStream;public class App1 {public static void main(String[] args) throws IOException {SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();AccountDao accountDao = sqlSession.getMapper(AccountDao.class);Account ac = accountDao.findById(1);System.out.println(ac);sqlSession.close();}
}
效果如下:
接下来,将直接使用配置类,通过注解的方式,直接实现spring与mybatis的使用:
第一:
创建配置类,SpringConfig
package com.wxy.config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;@Component
@ComponentScan("com.wxy")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {
}
第二,编写jdbc的config类:
package com.wxy.config;import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;import javax.sql.DataSource;public class JdbcConfig {@Value("${jdbc.driver}")private String driver;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Beanpublic DataSource dataSource(){DruidDataSource ds = new DruidDataSource();ds.setDriverClassName(driver);ds.setUrl(url);ds.setUsername(username);ds.setPassword(password);return ds;}
}
第三,编写mybatis的配置类(记得加上bean注解告诉spring进行扫描):
package com.wxy.config;import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;import javax.sql.DataSource;public class MybatisConfig {@Beanpublic SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();ssfb.setTypeAliasesPackage("com.wxy.domain");ssfb.setDataSource(dataSource);return ssfb;}@Beanpublic MapperScannerConfigurer mapperScannerConfigurer(){MapperScannerConfigurer mac = new MapperScannerConfigurer();mac.setBasePackage("com.wxy.dao");return mac;}
}
第四,可以直接编写测试类App2:
package com.wxy;import com.wxy.config.SpringConfig;
import com.wxy.domain.Account;
import com.wxy.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App2 {public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);AccountService accountService = ctx.getBean(AccountService.class);Account ac = accountService.findById(2);System.out.println(ac);}
}
效果如下:
总结:使用配置文件进行配置,就需要写xml文件,将需要配置的信息都进行填写。而使用配置类的进行配置时,则是使用Java代码填写在类中,通过注解的方式,告诉spring这是一个bean类需要扫描,从编码的角度,使用配置类填写的信息还是比配置文件少的,其实也更为直观。
下一篇: “咏桑寓柳”的意思