Spring boot 持久化(jdbc)
1.创建Maven项目
2.导jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- 数据库驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
3.数据库信息配置(application.properties)
########################################################
###datasource
########################################################
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
4.Dao层(impl)
@Repository
public class UserDaoImpl implements IUserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void save(User user) {
String sql="insert into user(name,age) values(?,?)";
jdbcTemplate.update(sql,user.getName(),user.getAge());
}
@Override
public List findAll() {
String sql="select * from user";
List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
return users;
}
}
5.Domain层
public class User {
private Long id;
private String name;
private Integer age;
...
6.Service层(impl)
@Service
public class UserServerImpl implements IUserServer {
@Autowired
private IUserDao userDao;
@Override
public void save(User user) {
userDao.save(user);
}
@Override
public List findAll() {
List<User> all = userDao.findAll();
return all;
}
}
7.创建一个启动类
@SpringBootApplication
@ComponentScan("com.lining.springcloud") //如果启动类和其他类不在一个目录下,需要进行扫描
public class JdbcApplication {
public static void main(String[] args) {
SpringApplication.run(JdbcApplication.class, args);
}
}
8.Spring Boot注解式事务
方式一(声明式):
<!-- 配置事物管理器 -->
<beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<propertyname="dataSource"ref="dataSource"/>
</bean>
<!-- aop应用事务管理 -->
<tx:adviceid="txAdvice"transaction-manager="transactionManager">
<tx:attributes>
<tx:methodname="find*"propagation="SUPPORTS"read-only="true"/>
<tx:methodname="get*"read-only="true"/>
<tx:methodname="select*"read-only="true"/>
<tx:methodname="search*"read-only="true"/>
<tx:methodname="query*"read-only="true"/>
<tx:methodname="*"propagation="REQUIRED"read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcutexpression="execution(* cn.itsource.eloan.core.service..*.*(..))"id="coreServicePointcut"/>
<aop:advisoradvice-ref="txAdvice"pointcut-ref="coreServicePointcut"/>
</aop:config>
原来实现:
1)事务管理器
2)开启注解,就是能够识别@Transactional
3)在要控制事务的Service的或方法上面加上@Transactional
建议:类级别为只读事务,需要写事务的方法上面加写事务