2.配置jdbc.propertiesorg.springframework spring-context5.2.10.RELEASE com.alibaba druid1.1.16 org.mybatis mybatis3.5.6 mysql mysql-connector-java5.1.47 org.springframework spring-jdbc5.2.10.RELEASE org.mybatis mybatis-spring1.3.0 org.projectlombok lombok1.18.12
3.配置JdbcConfigjdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test?useSSL=false jdbc.username=root jdbc.password=123456
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; @Bean public DataSource dataSource(){ DruidDataSource ds = new DruidDataSource(); ds.setDriverClassName(driver); ds.setUrl(url); ds.setUsername(userName); ds.setPassword(password); return ds; }4.配置MybatisConfig
public class MybatisConfig { //定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象 @Bean public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){ SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean(); ssfb.setTypeAliasesPackage("com.springmybatis.domain"); ssfb.setDataSource(dataSource); return ssfb; } //定义bean,返回MapperScannerConfigurer对象 @Bean public MapperScannerConfigurer mapperScannerConfigurer(){ MapperScannerConfigurer msc = new MapperScannerConfigurer(); msc.setbasePackage("com.springmybatis.dao"); return msc; }5.声明配置类
@Configuration @ComponentScan("com.springmybatis") //@PropertySource:加载类路径jdbc.properties文件 @PropertySource("classpath:jdbc.properties") @import({JdbcConfig.class,MybatisConfig.class}) public class SpringConfig { }6.案例结构
(1)案例的整体结构
数据表:
(2)实体类
@Data public class Books { int id; String name; String author; }
(3)dao层
public interface BooksDao { @Select("select * from books") Listfindall(); @Select("select * from books where id=#{id}") Books findbyid(int id); }
(3)service层
接口:
public interface BooksService { ListfindAll(); Books findById(int id); }
实现类:
@Service public class BooksServiceImpl implements BooksService { @Autowired BooksDao booksDao; public ListfindAll() { final List booksList = booksDao.findall(); return booksList; } public Books findById(int id) { final Books book = booksDao.findbyid(id); return book; } }
(4)主类
public class App { public static void main(String[] args) { ApplicationContext context=new AnnotationConfigApplicationContext(SpringConfig.class); final BooksService booksService = context.getBean(BooksService.class); final List7.测试all = booksService.findAll(); for (Books book : all) { System.out.println(book); } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)