------------I do not have him, but the hand is ripe, humble and foolish, and eager to be hungry-------------
A brief overview of this lecture
Alias, SQL Snippet write a little bit more, fuzzy query write more
One. Alias
<typeAliases> <!--first-- <!--<typealias type="Cn.dawn.demo01.entity.Book " alias="book"></typeAlias>--> <!--second -- <package name="cn.dawn.demo01.entity"></package> </ Typealiases>
Aliases are written in large configurations
Two. SQL fragment
In the development process generally do not directly use the * as SQL query statement column, because the loss of performance is serious, in many times, the column name is reused, but the column name is too many, so very troublesome, how to solve?
SQL fragment
How to use?
As follows:
<sql id="mysql"> bookid,bookname,bookauthor,bookprice </ sql><Select id="findonebookbypk" resulttype="book " > <include refid="mysql"/> from book WHERE bookid=#{bookid} </Select>
Use include to reference the column names in the SQL fragment past
Three. Fuzzy query
DAO layer
// Fuzzy query Public List<book> Likeselect (String bookname);
In small configurations
<sql id="MySQL">Bookid,bookname,bookauthor,bookprice</sql><!--Fuzzy Query-<!--cannot prevent SQL injection<SelectId="Likeselect"Parametertype="string"Resulttype=" Book">SELECT* FROM book WHERE bookname like'%${value}%'</Select>--> <!--can prevent SQL injection<SelectId="Likeselect"Parametertype="string"Resulttype=" Book">SELECT* FROM book WHERE bookname like'%'#{value}'%'</Select>--> <!--to prevent SQL injection---<SelectId="Likeselect"Parametertype="string"Resulttype=" Book">SELECT<include refid="MySQL"/> from book WHERE bookname like Concat ('%', #{bookname},'%') </Select>
Three ways, the first is not to prevent SQL injection (to finish the log consolidation from the console can see the SQL statement), I like the second kind of
In the test class
//Fuzzy Query@Test Public voidT6likeselect () {String path="Mybatis-config.xml"; Try{InputStream e=resources.getresourceasstream (path); Sqlsessionfactorybuilder Builder=NewSqlsessionfactorybuilder (); Sqlsessionfactory Factory=Builder.build (e); Sqlsession Session=factory.opensession (); Ibookdao Mapper= Session.getmapper (Ibookdao.class); List<Book> list = Mapper.likeselect ("of the"); for(book item:list) {System. out. println (Item.getbookname ()); } session.close (); } Catch(IOException var9) {var9.printstacktrace (); } }
The fuzzy query here is done, say getmapper it,
Before my several blogs, in the original way, he asked himself to test the class in the hand-play method, but now this through the Session.getmapper (DAO layer interface. Class) reflection to obtain the DAO layer of this interface implementation class, so you can use the strong type
The way, directly through the point of way point out for you to choose, the chance of error greatly reduced such as Mapper.findall ()
Aliases in Ssm-mybatis-05:mybatis, SQL fragment and fuzzy query plus Getmapper