一、项目创建
1、新建项目
2、导包 maven坐标下载后提取 导入WebContent/lib下,或用Add External JARs...导包(推荐,优点:不占项目空间,不重复导包)
不懂得用Add External JARs...导包,前往我的主页,看往期博客
3、包目录
二、Mysql项目准备
1、建库
2、sql语句 建表
DROP TABLE IF EXISTS `tb_account`;
CREATE TABLE `tb_account` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NULL DEFAULT NULL,
`money` double(255, 5) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_bin ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of tb_account
-- ----------------------------
INSERT INTO `tb_account` VALUES (1, 'Beddy', 783.56000);
INSERT INTO `tb_account` VALUES (2, 'Tom', 1000.75000);
INSERT INTO `tb_account` VALUES (3, 'Jerry', 893.65000);
SET FOREIGN_KEY_CHECKS = 1;
3、新建jdbc.properties
/GoodTestSpringMybatis/src/jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=(链接密码)
jdbc.url=jdbc:mysql://localhost:3307/<good_springmybatis>(数据库名)?useSSL=false&allowPublicKeyRetrieval=true
三、代码编写
1、实体类
/GoodTestSpringMybatis/src/com/example/domain/Account.java
package com.example.domain;
public class Account {
private int id;
private String name;
private Double money;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";
}
}
2、dao层 接口
(纯注解开发 相当于mapper层)
/GoodTestSpringMybatis/src/com/example/dao/AccountDao.java
package com.example.dao;
import java.util.List;
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 com.example.domain.Account;
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);
void delete(int id);
@Update("update tb_account set name = #{name}, money = #{money} where id = #{id} ")
void update(Account account);
@Select("select * from tb_account")
List<Account> findAll();
@Select("select * from tb_account where id = #{id} ")
Account findById(Integer id);
}
3、service层 接口
接口只需要定义方法,将bean给spring管理,不懂得我再出一期spring项目创建
/GoodTestSpringMybatis/src/com/example/service/AccountService.java
package com.example.service;
import java.util.List;
import com.example.domain.Account;
//接口只需要定义方法,将bean给spring管理
public interface AccountService {
public void save(Account account);
public void update(Account account);
public void delete(Integer id);
public Account findById(Integer id);
public List<Account> findAll();
}
4、创建service的impl 实现类
写方法的service接口方法的实现,通过 autowird自动封装dao层(mapper),调用 dao层的AccountDao的接口方法,如下:
/GoodTestSpringMybatis/src/com/example/service/impl/AccountServiceImpl.java
package com.example.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.dao.AccountDao;
import com.example.domain.Account;
import com.example.service.AccountService;
@Service
public class AccountServiceImpl implements AccountService{
@Autowired
private AccountDao accountDao;
public void save(Account account) { accountDao.save(account); }
public void update(Account account) { accountDao.update(account); }
public void delete(Integer id) { accountDao.delete(id); }
public Account findById(Integer id) { return accountDao.findById(id); }
public List<Account> findAll() { return accountDao.findAll(); }
}
四、完成pojo、dao、service 再继续下面步骤
五、配置JdbcConfig.java Druid连接池
/GoodTestSpringMybatis/src/com/example/config/JdbcConfig.java
package com.example.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import com.alibaba.druid.pool.DruidDataSource;
// 配置jdbc 充当配置文件 在 总的springconfig中导入它 @Import(JdbcConfig.class)
public class JdbcConfig {
//@Value是spring特有的 需要 在 SpringConfig.java中将jdbc.properties配置
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.password}")
private String password;
@Value("${jdbc.username}")
private String username;
@Bean
public DataSource dataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(driver);
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
/* // 连接池配置--默认可以不设
druidDataSource.setInitialSize(5); // 初始化连接数,默认为0
druidDataSource.setMinIdle(5); // 最小空闲连接数
druidDataSource.setMaxActive(20); // 最大活跃连接数
druidDataSource.setMaxWait(60000); // 获取连接的最大等待时间,单位毫秒
*/
return druidDataSource;
}
}
六、配置MybatisConfig.java Mybatis+Druid连接数据库
/GoodTestSpringMybatis/src/com/example/config/MybatisConfig.java
package com.example.config;
import javax.sql.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
public class MybatisConfig {
@Bean //添加自动装配注解
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
//<typeAliases>加载实体类
sqlSessionFactoryBean.setTypeAliasesPackage("com.example.domain");
//JdbcConfig @Bean DruidDataSource 加载jdb cdruid
sqlSessionFactoryBean.setDataSource(dataSource);//datasource造好了吗?
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
//添加自动装配注解
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//Mapper.xml Mapper.java (扫描dao层)
mapperScannerConfigurer.setBasePackage("com.example.dao");
return mapperScannerConfigurer;
}
}
七、重要——spring整合mybatis(SpringConfig.java)
/GoodTestSpringMybatis/src/com/example/config/SpringConfig.java
package com.example.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
@Configuration
@ComponentScan({"com.example"}) //扫描整个项目的有注解componet(包括@Service\@Controllerd等附属bean)
//@PropertySource(value = {"test.properties","jdbc.properties"}, encoding = "UTF-8")//导入多配置文件
@PropertySource(value = {"jdbc.properties"}, encoding = "UTF-8")//导入多配置文件
@Import({JdbcConfig.class,MybatisConfig.class})//加载先前的两个配置
public class SpringConfig {
}
八、编写main测试方法
厉害的友友可以用单元测试junit
/GoodTestSpringMybatis/src/com/example/Test.java
package com.example;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.example.config.SpringConfig;
import com.example.domain.Account;
import com.example.service.AccountService;
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext act = new AnnotationConfigApplicationContext(SpringConfig.class);
AccountService accountService = act.getBean(AccountService.class);
List<Account> all = accountService.findAll();
System.out.println(all);
act.close();
}
}
九、运行结果
服务层,accountService,调用了 dao层(mapper)findAll()方法实现查找数据库account表所有
十、关注我
目录结构