Linux CPU快取一致性
阿新 • • 發佈:2022-03-20
Mybatis 使用 Class、xml實現操作資料庫(基礎的javaProject)
jar包:mybatis-3.5.2.jar / mysql-connector-java-5.1.47.jar
目錄:src/mybatis/dao
建立mybatis-config.xml/NewsMapper.xml
建立類MybatisDrill
mybatis-config.xml
<?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> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/maven?useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mybatisClass/dao/NewsMapper.xml"/> </mappers> </configuration>
NewsMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace對應介面檔案 --> <mapper namespace="mybatisClass.dao.NewsMapper"> <!-- id是介面類裡的方法名 --> <!-- resultType是返回實體型別(帶包名) --> <select id="selectUser"> select * from user where id = #{id} </select> <insert id="insertUser"> insert into user values(#{id},#{password}) </insert> </mapper>
MybatisDrill
package mybatisClass; 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.InputStream; import java.util.HashMap; public class MybatisDrill { private static SqlSessionFactory sqlSessionFactory; public static void main(String[] args) throws Exception{ String resource = "mybatisClass/dao/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); selectUser(sqlSession); } public static void selectUser(SqlSession sqlSession){ HashMap<String,String> news = new HashMap<String,String>(); news.put("id","news"); news.put("password","520520"); int n = sqlSession.insert("mybatisClass.dao.NewsMapper.insertUser",news); sqlSession.commit(); sqlSession.close(); } }
實現的效果就是在資料庫的User表中插入了一行資料