SpringBoot Maven SSM整合 demo(中)

5、导入c3p0数据库连接池

在pom.xml中添加字句:
SpringBoot Maven SSM整合 demo(中)_第1张图片
保存后Maven会自动下载依赖包,注意等待右下角进度条完成。

6、配置DataSource数据源和SessionFactory

新建com.zzz.springboot_maven_ssm_demo.config包下,创建SSMConfiguration类,代码如下:

package com.zzz.springboot_maven_ssm_demo.config;

import java.beans.PropertyVetoException;
import java.io.IOException;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * @ClassName:  SSMConfiguration   
 * @Description:配置DataSource数据源和持久层的SessionFactory
 * @author Administrator
 * @date:   2022年3月21日 下午5:08:48      
 * @Copyright:
 */
 
@Configuration
@MapperScan("com.zzz.springboot_maven_ssm_demo.dao") //mapper的扫描路径
public class SSMConfiguration {
	
	//自动装配@Bean(name="dataSource")
	@Autowired
	private DataSource dataSource;

	@Bean(name="dataSource")
	public ComboPooledDataSource createDataSource() throws PropertyVetoException {
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		
		//driver url username password
		dataSource.setDriverClass("com.mysql.jdbc.Driver");
		dataSource.setJdbcUrl("jdbc:mysql://::1:3306/ssm_mybatis?serverTimezone=UTC&characterEncoding=utf-8&useSSL=true");
		dataSource.setUser("root");
		dataSource.setPassword("root");
		dataSource.setAutoCommitOnClose(false);
		
		return dataSource;
	}
	
	@Bean(name="sqlSessionFactory")
	public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		
		//加载主配置文件mybatis-config.xml
		bean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
		//Mapper扫描路径
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		String packageSearchPath = "classpath*:/mapper/**.xml";
		bean.setMapperLocations(resolver.getResources(packageSearchPath));
		//配置实体数据包
		bean.setTypeAliasesPackage("com.zzz.springboot_maven_ssm_demo.entity");
		//设置dataSource
		bean.setDataSource(dataSource);
		
		return bean;
	}
}

然后创建的工程目录结构如下:
SpringBoot Maven SSM整合 demo(中)_第2张图片
注意:一定要以com.zzz.springboot_maven_ssm_demo为根包。
mybatis-config.xml的配置内容如下:




<configuration>
	<settings>
		
		<setting name="useGeneratedKeys" value="true"/>
		
		<setting name="mapUnderscoreToCamelCase" value="true"/>
	settings>
configuration>

7、运行测试

对着com.zzz.springboot_maven_ssm_demo根包右键运行:
SpringBoot Maven SSM整合 demo(中)_第3张图片
控制台窗口出现Tomcat started字句就成功运行了。
SpringBoot Maven SSM整合 demo(中)_第4张图片

你可能感兴趣的:(Java,java,spring,maven)