// 我的第一个jdbc程序
public class JdbcFirstDemo {
public static void main(String[] args) throws Exception {
// 1.加载驱动
Class.forName("com.mysql.jdbc.Driver"); // 固定写法
// 2.用户信息和url
// useUnicode=true支持中文编码,characterEncoding=utf8字符编码,useSSL=true使用安全连接
String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
String username = "root"; // 连接数据库的用户名
String password = "qi"; // 连接数据库的密码
// 3.连接成功,数据库对象 Connection代表数据库
Connection connection = DriverManager.getConnection(url,username,password);
// 4.获得执行SQL的对象 Statement
Statement statement = connection.createStatement();
// 5.执行SQL的对象 去执行SQL可能存在的结果,查看返回结果
String sql = "select * from users";
/*
statement.executeQuery() 查询 *** 作返回ResultSet
statement.execute(sql) 执行任何SQL
statement.executeUpdate() 更新、插入、删除都是用这个,返回一个受影响的行数
*/
ResultSet resultSet = statement.executeQuery(sql); // 返回的结果集 结果集封装了我们全部查询出来的结果
/*
getObject()在不知道类型的情况下使用,如果知道类型就用指定类型,比如getString()
resultSet.beforeFirst() 移动到最前面
resultSet.afterLast() 移动到最后面
resultSet.next() 移动到下一行数据
resultSet.previous() 移动到前一行
resultSet.absolute() 移动到指定行
*/
while(resultSet.next()){
System.out.println("id="+resultSet.getObject("id"));
System.out.println("NAME="+resultSet.getObject("NAME"));
System.out.println("PASSWORD="+resultSet.getObject("PASSWORD"));
System.out.println("email="+resultSet.getObject("email"));
System.out.println("birthday="+resultSet.getObject("birthday"));
}
// 6.释放连接(耗资源,用完关掉)
resultSet.close();
statement.close();
connection.close();
}
}
2.Mybatis
2.1mybatis-config配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--引入外部配置文件-->
<properties resource="db.properties"/>
<settings>
<!--标准的日志工厂实现-->
<setting name="logImpl" value="STDOUT_LOGGING "/>
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
<!--起别名-->
<typeAliases>
<typeAlias type="com.test.pojo.User" alias="User"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--这里不是点是斜杠-->
<mapper resource="com/test/dao/UserMapper.xml"/>
</mappers>
</configuration>
2.2Mapper配置
<?xml version="1.0" encoding="utf8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--绑定一个对应的Mapper接口-->
<mapper namespace="com.test.dao.UserMapper">
<!--
id:对应的namespace的方法名
resultType:SQL语句执行的返回值
parameterType:参数类型
-->
<!--idea右边连上数据库才能用数据库.表名-->
<select id="getUserList" resultType="com.test.pojo.User">
select * from mybatis.user
</select>
<!--根据ID查询用户-->
<select id="getUserById" parameterType="int" resultType="com.test.pojo.User">
select * from mybatis.user where id = #{id}
</select>
<!--插入一个用户-->
<!--对象中的属性可以直接取出来-->
<insert id="addUser" parameterType="com.test.pojo.User">
insert into user(id,name,pwd) values(#{id},#{name},#{pwd})
</insert>
<!--修改用户信息-->
<update id="updateUser" parameterType="com.test.pojo.User">
update mybatis.user set name = #{name},pwd = #{pwd} where id = #{id}
</update>
<!--只修改用户密码-->
<!--传递map的key-->
<!--扫描包的方式可以通过首字母小写起别名,这里的map相当于java.util.Map-->
<update id="updateUser2" parameterType="map">
update mybatis.user set pwd = #{pwd} where id = #{id}
</update>
<!--删除一个用户-->
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id}
</delete>
<!--查询姓李的人-->
<select id="getUserByName" parameterType="String" resultType="com.test.pojo.User">
select * from user where name like "%"#{name}"%"
</select>
</mapper>
2.3工具类
package com.test.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static{
// 使用mybatis第一步:获取sqlSessionFactory对象
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
// 既然有了sqlSessionFactory,顾名思义,我们就可以从中获得SqlSession的实例了。
// SqlSession完全包含了面向数据库执行SQL命令所需的所有方法
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
2.4 所需依赖以及相关配置pom.xml
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<!--在bulid中配置resources,来防止我们资源导出失败问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
3.Spring
3.1 spring整合mybatis
3.1.1spring中配置mybatis(注意需要spring配置mybatis文件,mapper接口以及xml文件和实现类)
<?xml version="1.0" encoding="utf8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--DataSource:使用Spring的数据源替换Mybatis的位置 c3p0 dbcp druid
我们这里使用Spring提供的JDBC:org.springframework.jdbc.datasource
-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="li"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<!--绑定Mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/test/mapper/UserMapper.xml"/>
</bean>
<!--sqlSession-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入sqlSessionFactory,因为他没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<bean id="userMapper" class="com.test.mapper.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
</bean>
<bean id="userMapper2" class="com.test.mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
3.1.2 mapper包的实现类
public class UserMapperImpl implements UserMapper{
// 以前我们所有的 *** 作都是用sqlSession来执行,现在我们都使用sqlSessionTemplate
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
@Override
public List<User> queryUser() {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.queryUser();
}
}
3.2 配置事务
在上述bean文件上加入
<!--配置声明事务-->
<bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"/>
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务通知:-->
<tx:advice id="txAdvice" transaction-manager="transactionManger">
<!--给哪些方法配置事务-->
<!--配置事务的传播特性 : new progation=-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.test.mapper.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
3.3 所需jar包
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<!--spring *** 作数据库需要一个spring-jdbc包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
</dependencies>
<!--在bulid中配置resources,来防止我们资源导出失败问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)