两种数据库连接⽅式两种注解(注解版usermapper,⽂件
版)
⼀、两种连接数据库的⽅式
⽅式⼀:
springboot默认配置了(DataSource和sqlsessionfactory)
直接配置⽂件l
⾥⾯写
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/o2odb?serverTimezone=UTC&characterEncoding=utf-8&useSSL=true
driver-class-name: sql.jdbc.Driver
username: root
password: root
⽅式⼆:
类似springmvc 配置datasource和 sessionfactory,然后 写⼊⼀个bean加⼊到容器。
application.properties⾥⾯如下
jdbc.sql.jdbc.Driver
jdbc.url= jdbc:mysql://localhost:3306/o2odb?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
然后新建两个config
hange.v2.c3p0.ComboPooledDataSource;
batis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import t.annotation.Bean;
import t.annotation.Configuration;
import java.beans.PropertyVetoException;
@Configuration
@MapperScan("dao")
public class DataSourceConfiguration {
@Value("${jdbc.driver}")
private String jdbcDriver;
@Value("${jdbc.url}")
private String jdbcUrl;
@Value("${jdbc.username}")
private String jdbcUsername;
@Value("${jdbc.password}")
private String jdbcPassword;
@Bean(name = "dataSource")
public ComboPooledDataSource createDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
//dirver
dataSource.setDriverClass(jdbcDriver);
//url
dataSource.setJdbcUrl(jdbcUrl);
//username
dataSource.setUser(jdbcUsername);
//password
dataSource.setPassword(jdbcPassword);
//在关闭连接之后不会⾃动的Commit
dataSource.setAutoCommitOnClose(false);
//  <!--当连接池中的连接耗尽的时候c3p0⼀次同时获取的连接数。Default: 3 -->
dataSource.setAcquireIncrement(5);
// <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
dataSource.setAcquireRetryAttempts(30);
/
/ <!--两次连接中间隔时间,单位毫秒。Default: 1000 -->
dataSource.setAcquireRetryDelay(1000);
// <!-- 当连接池⽤完时客户端调⽤getConnection()后等待获取新连接的时间,超时后将抛出SQLException        dataSource.setCheckoutTimeout(10000);
dataSource.setMaxStatements(0);
//<!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。 Default: 3 -->
dataSource.setInitialPoolSize(10);
dataSource.setMinPoolSize(5);
//    <!--连接池中保留的最⼤连接数。Default: 15 -->
dataSource.setMaxPoolSize(200);
// <!--最⼤空闲时间,60秒内未使⽤则连接被丢弃。若为0则永不丢弃。Default: 0 -->
dataSource.setMaxIdleTime(60);
//<!--How long to hang on to excess unused connections after traffic spike -->
dataSource.setMaxIdleTimeExcessConnections(600);
return dataSource;
}
}
batis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import t.annotation.Bean;
import t.annotation.Configuration;
import io.ClassPathResource;
import io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
import java.io.IOException;
@Configuration
public class SessionFactoryConfiguration {
@Autowired
private DataSource dataSource;
@Bean(name="sqlSessionFactory")
public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException
{
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
//加载主配置⽂件l
bean.setConfigLocation(new ClassPathResource("l"));
//Mapper扫描路径
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();        String packageSearchPath = "classpath*:/mapper/**.xml";
bean.Resources(packageSearchPath));
//配置实体的包
bean.setTypeAliasesPackage("com.del");
//dataSource
bean.setDataSource(dataSource);
return bean;
}
}
启动即可。
⼆、两种和数据库打交道
@RestController
public class wenjianversioncontroller {
@Autowired
private UserDao userDao;
@RequestMapping("/wenjianfindall")
public String wenjianfindall(){
List<User> users = userDao.searchAllUsers();
for (User user : users) {
System.out.Id()+"--"+Username()+""+Password());
}
userDao.deleteUserById(2);
return "wenjianfindall";
}
public interface UserDao {
//增
int addUser(User user);
//删
//int deletUser(User user);
int deleteUserById(int id);
//改
int updateUser(User user);
//查
List<User> searchAllUsers();
User searchUserById(int id);
}
然后resource⾥⾯的mapper⾥⾯
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN"
"/dtd/mybatis-3-mapper.dtd">
<!-- namespace:Mapper对应的DAO -->
<mapper namespace="com.hy.oa.dao.UserDao">
<!--  select:查询⼦句
id:对应的⽅法名称
resultType: 返回的类型-->
<select id="searchAllUsers" resultType="com.del.User">
select * from user
</select>
<select id="searchUserById" resultType="com.del.User">
select * from user where id = #{id}
</select>
<!-- userGeneratedKeys:如果执⾏成功,则返回主键的值,parameterType:⼊参的类
<insert id="addUser1" useGeneratedKeys="true">
insert into user(username,password) values(#{username},#{password})
</insert>-->
<insert id="addUser" useGeneratedKeys="true" keyProperty="id" keyColumn="id" parameterType="com.del.User">  insert into user values(#{id},#{username},#{password})
</insert>
<update id="updateUser" parameterType="com.del.User">
update user set username=#{username},password=#{password} where id=#{id}
resource和autowired注解的区别</update>
<delete id="deleteUserById">
delete from user where id = #{id}
</delete>
<!--<delete id="deleteUserById2">
delete from user where id = #{Lain}
</delete>-->
</mapper>
----------------------------------
⽅式⼆:
dao⾥⾯直接注解,然后注解⾥⾯写sql语句。
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("select * from user")
List<User> findAll();
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。