pox.xml 导入包
<dependency> <groupId>junit</groupId> <!--junit单元测试--> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <!--junit单元测试--> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>compile</scope> </dependency> <dependency> <!--mybatis 依赖--> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <!--mysql 依赖--> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.48</version> </dependency> <dependency> <!--log 日志--> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.12.1</version> </dependency> <dependency> <!--log 日志--> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.12.1</version> </dependency> <dependency> <!-- druid 阿里提供的mysql连接池 --> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.21</version> </dependency> <dependency> <!--commons-logging jdbc template 需要的包--> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <!--commons-logging jdbc template 需要的包--> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.2.5.RELEASE</version> </dependency> <dependency> <!--spring-core jdbc template 需要的包--> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.2.5.RELEASE</version> </dependency> <dependency> <!--spring-jdbc jdbc template 需要的包--> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.5.RELEASE</version> </dependency> <dependency> <!--spring-tx jdbc template 需要的包--> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.2.5.RELEASE</version> </dependency>
创建resources文件夹 放置配置文件
resources-->druid.properties 数据库配置文件
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://10.133.3.26:3306/mybatis_test?useUnicode=true&characterEncoding=utf8&useSSL=false username=root password=root # 初始化连接数量 initialSize=5 # 最大连接数 maxActive=10 # 最大等待时间 maxWait=3000
resources-->log4j2.xml 日志配置文件
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN"> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n"/> </Console> <RollingFile name="RollingFile" filename="log/test.log" filepattern="${logPath}/%d{YYYYMMddHHmmss}-fargo.log"> <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n"/> <Policies> <SizeBasedTriggeringPolicy size="10 MB"/> </Policies> <DefaultRolloverStrategy max="20"/> </RollingFile> </Appenders> <Loggers> <Root level="info"> <AppenderRef ref="Console"/> <AppenderRef ref="RollingFile"/> </Root> </Loggers> </Configuration>
创建java-->utils文件夹
java-->utils-->JDBCUtils jdbc普通封装
package mysql.java.utils; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; // Druid连接池的工具类 public class JDBCUtils { //1.定义成员变量 DataSource private static DataSource ds; static { try { //1.加载配置文件 Properties pro = new Properties(); pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties")); //2.获取DataSource ds = DruidDataSourceFactory.createDataSource(pro); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } // 获取连接 public static Connection getConnection() throws SQLException { return ds.getConnection(); } // 释放资源 public static void close(Statement stmt, Connection conn) { close(null, stmt, conn); } public static void close(ResultSet rs, Statement stmt, Connection conn) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close();//归还连接 } catch (SQLException e) { e.printStackTrace(); } } } // 获取连接池方法 public static DataSource getDataSource() { return ds; } }
domain --> Emp.java object对象
package mysql.domain; import java.util.Date; public class Emp { private Integer id; private String username; private Date birthday; private String sex; private String address; @Override public String toString() { return "Emp{" + "id=" + id + ", username='" + username + '\'' + ", birthday=" + birthday + ", sex='" + sex + '\'' + ", address='" + address + '\'' + '}'; } public void setId(Integer id) { this.id = id; } public void setUsername(String username) { this.username = username; } public void setBirthday(Date birthday) { this.birthday = birthday; } public void setSex(String sex) { this.sex = sex; } public void setAddress(String address) { this.address = address; } public Integer getId() { return id; } public String getUsername() { return username; } public Date getBirthday() { return birthday; } public String getSex() { return sex; } public String getAddress() { return address; } public Emp(Integer id, String username, Date birthday, String sex, String address) { this.id = id; this.username = username; this.birthday = birthday; this.sex = sex; this.address = address; } public Emp() { } }
jdbctemplate --> JdbcTmpalateDome.java 数据库操作
package mysql.jdbctemplate; import mysql.domain.Emp; import mysql.java.utils.JDBCUtils; import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; public class JdbcTemplateDome01 { private JdbcTemplate template; @Before public void init() { template = new JdbcTemplate(JDBCUtils.getDataSource()); // 获取JDBCTemplate对象 } @Test public void selectSql() { // 查询数据 String sql = "UPDATE user set address=? WHERE id=?"; int count = template.update(sql, "杭州", "49"); System.out.println(count); } @Test public void insterSql() { // 插入一条数据 String sql = "INSERT INTO user(username, birthday, sex, address) values(?, ?, ?, ?)"; String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); int count = template.update(sql, "yoyo", date, "男", "上海"); System.out.println(count); } @Test public void deleteSql() { // 删除一条数据 String sql = "DELETE from user WHERE id=?"; int count = template.update(sql, 50); System.out.println(count); } /** * queryForMap:查询结果将结果集封装为map集合,将列名作为key,将值作为value 将这条记录封装为一个map集合 * 这个方法查询的结果集长度只能是1 */ @Test public void selectMap() { // 查询一条数据 封装成map集合 String sql = "select * from user where id=?"; Map<String, Object> map = template.queryForMap(sql, 49); System.out.println(map); } /** * queryForList:查询结果将结果集封装为list集合 * 将每一条记录封装为一个Map集合,再将Map集合装载到List集合中 */ @Test public void selectListMap() { // 查询所有数据封装为list String sql = "select * from user"; List<Map<String, Object>> mapList = template.queryForList(sql); for (Map<String, Object> map : mapList) { System.out.println(map); } } /** * query:查询结果,将结果封装为JavaBean对象 * uery的参数:RowMapper * 一般我们使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的自动封装 * new BeanPropertyRowMapper<类型>(类型.class) */ @Test public void selectListEnp() { // 查询所有记录,将其封装为Emp对象的List集合 String sql = "select * from user"; List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class)); for (Emp emp : list) { System.out.println(emp); } } /** * queryForObject:查询结果,将结果封装为对象 * 一般用于聚合函数的查询 */ @Test public void selectObject() { // 查询总记录数 String sql = "select count(id) from user"; Long total = template.queryForObject(sql, Long.class); System.out.println(total); } }