In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces how to use Prepared Statement and symbols in Mybatis. It is very detailed and has certain reference value. Friends who are interested must finish reading it.
First, use a PreparedStatementimport java.math.BigDecimal;import java.sql.*;/** * @ author to find more wonderful official accounts: Muzi's round-the-clock programming * an unworldly programmer living at the bottom of the Internet, doing additions, deletions, changes and searches, * @ create 2021-08-25 21:26 * / public class TestMain {public static void main (String [] args) throws Exception {Connection conn = null; PreparedStatement stmt = null ResultSet result = null; try {/ / 1. Register the driver Class.forName ("com.mysql.jdbc.Driver"); / / 2. Open the connection url, user name, password conn = DriverManager.getConnection ("jdbc:mysql://127.0.0.1:3306/test?useSSL=false", "root", "123456"); / / 3. Create Statenebt stmt = conn.prepareStatement ("select * from test where name =?"); / / 4. Note that the parameter subscript starts from 1, not 0 stmt.setString (1, "Xiaoqiang"); / / 5. Execute the query result = stmt.executeQuery (); / / 6. Output the result obtained in the database while (result.next ()) {/ / get the value String name = result.getString ("name") based on the column name; BigDecimal salary = result.getBigDecimal ("salary"); System.out.println (salary of name+ "is:" + salary) }} catch (Exception e) {e.printStackTrace ();} finally {/ / close the resource / / close the resource try {if (resulting resources null) {result.close () }} catch (SQLException se2) {System.err.println ("close result exception");} try {if (stmtasking null) {stmt.close () }} catch (SQLException se2) {System.err.println ("close stmt exception");} try {if (connexual null) {conn.close () }} catch (SQLException se) {System.err.println ("close conn exception");} II. Use one-use Statementimport java.math.BigDecimal;import java.sql.* / * * @ author found more highlights about official account: Muzi's round-the-clock programming * A programmer living at the bottom of the Internet, doing additions, deletions, changes and queries, unworldly affectation * / public class TestMain02 {public static void main (String [] args) throws Exception {Connection conn = null; Statement stmt = null; ResultSet result = null; try {/ / 1. Register the driver Class.forName ("com.mysql.jdbc.Driver"); / / 2. Open the connection url, user name, password conn = DriverManager.getConnection ("jdbc:mysql://127.0.0.1:3306/test?useSSL=false", "root", "123456"); / / 3. Create Statenebt stmt = conn.createStatement (); / / 4. Execute the query result = stmt.executeQuery ("select * from test where name = 'Xiaoqiang'"); / / 5. Output the result obtained in the database while (result.next ()) {/ / get the value String name = result.getString ("name") based on the column name; BigDecimal salary = result.getBigDecimal ("salary"); System.out.println (salary of name+ "is:" + salary) }} catch (Exception e) {e.printStackTrace ();} finally {/ / close the resource / / close the resource try {if (resulting resources null) {result.close () }} catch (SQLException se2) {System.err.println ("close result exception");} try {if (stmtasking null) {stmt.close () }} catch (SQLException se2) {System.err.println ("close stmt exception");} try {if (connexual null) {conn.close () }} catch (SQLException se) {System.err.println ("close conn exception");} III. Use of Mybatis # {} ${}
# {} use
/ / # {} query data List listByName01 (String name) by name; select * from test where name = # {name} import dao.TestMapper;import entity.TestEntity;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.List / * * @ author found more highlights about official account: Muzi's round-the-clock programming * A programmer living at the bottom of the Internet, doing additions, deletions, changes and queries, unworldly affectation * / public class TestMain03 {public static void main (String [] args) throws Exception {String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream (resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). Build (inputStream) Try (SqlSession session = sqlSessionFactory.openSession ()) {/ / get Mapper through sesson this Mapper will program Mybatis's agent Mapper TestMapper mapper = session.getMapper (TestMapper.class); / / 1.# {} List res = mapper.listByName01 ("Xiaoqiang") / / sql executed: select * from test where name = 'Xiaoqiang' System.out.println ("number of first query entries:" + res.size ()); List res02 = mapper.listByName01 ("Xiaoqiang or 1q1") / / sql executed: select * from test where name = 'Xiaoqiang or 1q1' System.out.println ("number of second query entries:" + res02.size ());}
${} use
/ / ${} query data List listByName02 (@ Param ("name") String name) by name; select * from test where name = ${name} import dao.TestMapper;import entity.TestEntity;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.List / * * @ author found more highlights about official account: Muzi's round-the-clock programming * A programmer living at the bottom of the Internet, doing additions, deletions, changes and queries, unworldly affectation * / public class TestMain04 {public static void main (String [] args) throws Exception {String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream (resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). Build (inputStream) Try (SqlSession session = sqlSessionFactory.openSession ()) {/ / get Mapper through sesson this Mapper can program Mybatis's agent Mapper TestMapper mapper = session.getMapper (TestMapper.class); / / 1.$ {} you have to put your own single quotation marks or sql will be wrong List res = mapper.listByName02 ("Xiaoqiang") / / sql executed: select * from test where name = 'Xiaoqiang' System.out.println ("first time:" + res.size ()); List res02 = mapper.listByName02 ("'Xiaoqiang' or 1 # 1"); / / executed sql (scary): select * from test where name = 'Xiaoqiang' or 1 # 1 System.out.println ("second time:" + res02.size ()) }}}
# {} uses PrepareStatment and uses'?' Placeholders will not be injected by SQL. Whatever you output will be enclosed in single quotation marks.
Something like this:
Public class TestMain05 {public static void main (String [] args) {String sql = "select * from test where name ='?'"; String name = "Xiaoqiang"; sql = sql.replace ("?", name); System.out.println (sql); / / select * from test where name = 'Xiaoqiang'}}
${} it is equivalent to ordinary splicing. Whatever you pass in will be put to you intact behind the Sql.
Something like this:
Public class TestMain06 {public static void main (String [] args) {String sql = "select * from test where name =?"; String name = "Xiaoqiang"; sql = sql.replace ("?", name); System.out.println (sql);}} the difference between four and ResultMap ResultType
We have used resultType many times. Here is the next way to use resultMap.
Select * from test
ResultType and resultMap are similar in function, returning object information, but resultMap is more powerful and can be customized.
In general, databases in our projects are underlined, such as course_date, but courseDate is used in entity classes, so most of the time name matching is needed and aliases such as resultMap or sql are used.
Sql alias method:
Select id as id name as name age as age course_date as courseDate from test
Id&result
Both of them are attributes or fields that map a list of values to a simple data type (String, int, double, Date, and so on).
The only difference between them is that the attribute corresponding to the id element is marked as the identifier of the object, which is used when comparing object instances. This improves overall performance, especially when caching and nesting result mapping.
They both have some attributes:
The attribute describes the column name in the field or property column database that the property maps to the column result, or an alias for the column. Typically, this is the same as the parameters passed to the resultSet.getString (columnName) method.
Is the database column name javaType the fully qualified name of a Java class, or a type alias that can usually be inferred if you map to a JavaBean,MyBatis. However, if you are mapping to HashMap, then you should explicitly specify javaType to ensure that the behavior is consistent with expectations. JdbcType this is the type corresponding to the database, the non-essential typeHandler result handler, which is to process the result again and return it to the next few articles to write a custom typeHandler.
Find an example on the Chinese official website:
Constructor: when instantiating a class, inject the result into the constructor
IdArg: this is the primary key ID
Arg: this is the normal field.
Association: a field is an object in a complex type of associated object
Collection: a field in a complex type associated object is a collection
Discriminator: use the result value to confirm which resultMap to use
The above is all the content of the article "how to use Prepared Statement and symbols in Mybatis". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.