Sunteți pe pagina 1din 26

Venkat Krishnan -> http://evenkat.

com

1] public interface MessageDestination { void write(String m);} public interface MessageSource {String getTheMessage();} public class SimpleMessageDestination implements MessageDestination { public void write(String m) {System.out.println(m); } } public class SimpleMessageSource implements MessageSource { private String mess; SimpleMessageSource(){ mess="CBIT2"; System.out.println("Constructor called"); } public String getTheMessage() {return mess; } } PropertiesBeanDefinitionReader has the details bean.properties --> src destination.(class)=core.SimpleMessageDestination source.(class)=core.SimpleMessageSource Jar Files: Common Loggings, core, beans public class Main { public static void main(String[] args) { DefaultListableBeanFactory dbf = new DefaultListableBeanFactory(); BeanDefinitionReader dbr = new PropertiesBeanDefinitionReader(dbf); dbr.loadBeanDefinitions(new ClassPathResource("bean.properties")); MessageSource ms=(MessageSource)dbf.getBean("source"); MessageDestination md=(MessageDestination)dbf.getBean("destination"); czxmd.write(ms.getMessage()); System.out.println("Second time"); MessageSource ms1=(MessageSource)dbf.getBean("source"); MessageDestination md1=(MessageDestination)dbf.getBean("destination");
Page 1 of 26

Venkat Krishnan -> http://evenkat.com

md1.write(ms1.getMessage()); 2] Adding a service layer to MS and MD 3] Passing values dynamically from the properties file 4] Writing the contents to a file. 5] Show how to use XML as a DD. using XMLBeanFactory and inner beans public interface Oracle { String define();} public interface Encyclo1{Long findLong(String e); } public class DefaultOracle implements Oracle { Encyclo1 enc; public void setEnc(Encyclo1 enc) { this.enc = enc; } public String define() { Long a = enc.findLong("A");Long b = enc.findLong("B");return String.valueOf(a/b); }} public class DefaultEncyclo1 implements Encyclo1 { private Map<String,Long>m = new HashMap<String, Long>(); public DefaultEncyclo1(){ m.put("A", 100L); m.put("B", 10L); } public Long findLong(String e) {return m.get(e);} } public class Main { public static void main(String[] args) { XmlBeanFactory x = new XmlBeanFactory( new ClassPathResource("dynamic.xml")); Oracle o=(Oracle)x.getBean("oracle"); System.out.println(" The new value is "+ o.define()); } <bean id="oracle" class="core.DefaultOracle"> <property name="enc"> <bean class="core.DefaultEncyclo1"/> </property> </bean> </beans> 6] How to pass values from the XML file <bean id="encycl" class="core.DynamicEncyclo"> <constructor-arg>
Page 2 of 26

Venkat Krishnan -> http://evenkat.com

<util:map> <entry key="A" value="200"/> <entry key="B" value="100"/> </util:map> </constructor-arg> </bean> <bean id="oracle" class="core.DefaultOracle"> <property name="enc" ref="encycl"></property> </bean> 7] creating a person interface having the display function and then creating a programmer class having String name, int age, float height, boolean javaProgrammer, Long ageinseconds. Have setter methods in this class and override the display function to print the values of the variables. 8] create a DotnetProgrammer class having String name, int experience and boolean advanceConcepts which implements the person interface and initiaze the class variables with a Constructor and DO NOT have setter methods here. 9] Over Loading the Constructors 10] @Service, @Autowired and ApplicationContext. For injecting a value the use of setter does not work if @Service is used

Page 3 of 26

Venkat Krishnan -> http://evenkat.com

interface IWriter{ void write(String s);} @Service class DefaultWriter implements IWriter{ public void write(String s){System.out.println(s);} } @Service public class MySpringInject{ IWriter writ; IWriter writ1; @Autowired public void setWriter(IWriter i){writ = i;} public void execute(String s){writ.write(s);} }} public class Main{ public static void main(String s[]){ ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); MySpringInject x = (MySpringInject)ctx.getBean("mySpringInject"); x.execute("Hi"); }} beans.xml xmlns:context="http://www.springframework.org/schema/contex t" <context:component-scan base-package="core"/>

11] Autowire by Name --> The bean id name should be the same as the name of the property and the setter method should also have the same name 12] Autowire by Type --> The bean id name, property name and the setter method names can all be different

Page 4 of 26

Venkat Krishnan -> http://evenkat.com

12] Autowire by Constructor -> to be used when one Object should be created and ready when another one is created like Student should be ready when College object is created class EmpDao{ public void met1(){System.out.println("Test");} } class EmpManager{ EmpDao dao; --> setter public void met2(){dao.met1();} } class Main{ PSVM{ EmpManager v = (EmpManager)ctx.getBean("manager"); v.me2(); }} beans.xml 1] <bean id="manager"class = "core.EmpManager" <property name="dao" ref="empdao"/> <bean id = "empdao" class="core.EmpDao"> 2] <bean id="manager" class = "core.EmpManager" autowire="byName"> <bean id = "empdao" class="core.EmpDao"> --> will not work <bean id = "dao" class="core.EmpDao"> --> will work 3] <bean id = "empmanager" class="core.EmpManager" autowire="byType">

13] Bean Inheritance public class PersonBase { protected String fname; --> setter
Page 5 of 26

Venkat Krishnan -> http://evenkat.com

protected String lname; --> setter public String toString() { return "PersonBase [fname=" + fname + ", lname=" + lname + "]"; }} public class PersonAddress extends PersonBase { private String zipcode; --> setter method Have a toString which prints fname, lname and zipcode public class PersonSalary extends PersonBase{ int salary; --> setter method Have a toString which prints fname, lname and salary public class Main{ PersonAddress pa = (PersonAddress)ctx.getBean("padd") PersonSalary ps = (PersonSalary) ctx.getBean("psal"); Sop -> pa and ps In the XML file create a bean for PersonBase, PersonSalary and PersonAddress and pass the property values as defined in java a) How to specify relationship between objects in Bean file. [parent attribute="id of the bean"] a.a) if the bean has abstract as true can we use getBean on that?[no] b) Should there be extends in java file and parent attributes is there in the bean file for another bean [yes] c) if a bean is abstract, should the java class should be abstract? [no] d) if a java class is abstract should there be abstract attribute in the bean tag? [yes] 14] Bean LifeCycle abstract class Product --> name and price
Page 6 of 26

Venkat Krishnan -> http://evenkat.com

class Battery extends Product --> toString "Battery "name, price class Disk extends Product --> toString "Disk" name, price class Cashier --> name and path + BufferedWriter w setter methods for name and path method--> openFile(){ File f = new File(path,name+".txt"); w = new BufferedWriter (new OutputStreamWriter(new FileOutputStream(f,true))); } method-->checkout(ShoppingCart sc){ double total=0; for (Product p : sc.getItems()){ total += Double.parseDouble(p.getPrice()); } w.write(new Date()+" = "+ total+"\n"); w.flush(); method --> close(){w.close(); SOP("Called");} } class ShoppingCart --> List<Product> items = new ArrayList --> addItem(Product p) { items.add(p)} --> List getItems { return items;} XML <bean id = a class = "core.Battery"> -->name and price (property) <bean id = cd class = "core.Disk"> -->name and price (property) <bean id = dvd class = "core.disk"> -->name and price (property) <bean id = sc class="core.ShoppingCart> <bean id = ca class = "core.Cashier"> name and path(property) Main Product p1 = ac.getBean("a"); Product p2 = ac.getBean("cd"); Product p3 = ac.getBean("dvd"); ShoppingCart sc = Cashier ca = sc.addItem(p1);sc.addItem(p2);sc.addItem(p3); ca.checkout(sc);
Page 7 of 26

Venkat Krishnan -> http://evenkat.com

a) Get an error on w; NullPointer Exception b) implements DisposableBean, InitializingBean and over ride the methods and in afterPropertiesSet method call openFile c) the destroy method is not by default since the container is not shut down and we can forcefully call it by using AbstractApplicationContext class method called registerShutdownHook() d) use @PreDestroy and @PostConstruct before the methods which performs initialization and destruction and write <xmlns:context="http://www.springframework.org/schema/conte xt"> <xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/springcontext.xsd " <context:annotation-config/> e) Create two more products using getBean after the checkout to simulate a different user. Create one more ShoppingCart Object using getBean and add the 2 products to the new Shopping Cart and then call sc.getItems(). How many products should be show for the second user? e.1) How to do the same for annotation? f) Write total amount to a properties file and the location of the directory should be dynamic. <bean id="cashier" class="core.cashier"> <property name="path" value="${cas.path}"/> <context:property-placeholder location="config.properties" /> config.properties file write cas.path=c:\

Page 8 of 26

Venkat Krishnan -> http://evenkat.com

15] com.springsource.org.aopalliance-1.0.0, aop jar, cglib jar files AOP public class AdvisedObject { void print(){System.out.println("Hello");} } public class BeforeAdvice implements MethodBeforeAdvice { public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable { System.out.println("Testing"); System.out.println(arg0.getName()); }} public static void main(String[] args) { AdvisedObject a = new AdvisedObject(); ProxyFactory pf = new ProxyFactory(); pf.setTarget(a); pf.addAdvice(new BeforeAdvice()); AdvisedObject a1 = (AdvisedObject)pf.getProxy(); a1.print(); 16] Example showing Annotation @Aspect, @Before <aop:aspectj-autoproxy> interface Operation --> long operate(long a, long b) --> String getOperationName(); class OperationMultiply implements Operation --> operate (return a * b); --> getOperationName ( return "multiply") @Aspect class Logging Aspect{ @Before ("execution(* core.*.operate(..))") public void logMethod(JoinPoint jp){ SOP ("AOP Loggin " + jp.toShortString()); }} class Calculate{ Operation op; --> setter void execute(int a, int b){op.operate(a,b); op.getOperationName(); }} Main
Page 9 of 26

Venkat Krishnan -> http://evenkat.com

Calculate c= (Calculate)ac.getBean("calculate"); c.execute(args[0], args[1]); beans.xml <context:annotation-config> or component-scan <bean id ="opn" class="core.OperationMultiply"> <bean id ="cal" class="core.Calculate"> either --> <property> or autowire="byType" <aop:aspectj-autoproxy> <bean id="log" class="core.LogginAspect"/> 17] interface Basic void getAfter(); String getBefore(String s); Long getAround(String s) class BasicImpl implements Basic getAfter--> SOP getBefore --> SOP return s getAround --> SOP return 20L class BasicAspect public void beforeMethod(){SOP} public void afterMethod(){SOP} public Object aroundMethod(ProceedingJoinPoint jp){ sop("In Around advice"); Object op = jp.proceed(); String methodname = jp.getSignature().getName(); if("getBefore".equals(methodname)){ return "Wow this is new in Around Advice" } else if("getAround".equals(methodname)){ return 50L;} } Main class getBean and then call b1 (Basic) all 3 methods XML File--> <bean id="basicimpl" class> <bean id="basicaspect" class> <aop:config><aop:aspect ref="basicaspect"> <aop:pointcut id="pc1" expression= "execution(* core.*.getBefore(..))"> <aop:before pointcut-ref="pc1" method="beforeMethod"/></aop:pointcut>
Page 10 of 26

Venkat Krishnan -> http://evenkat.com

variations 1] <aop:pointcut id="pc2" expression= "execution(* core.*.getAfter(..))"> <aop:before pointcut-ref="pc2" method="afterMethod"/> 2] <aop:pointcut id="pc3" expression= "execution(* core.*.getAround(..))"> <aop:around pointcut-ref="pc3" method="aroundMethod"/> WSDL [Web Service Description Language] UDDI [Universal Discovery Description Interchange] SOAP [Simple object access protocol] XML 18] Sample MVC Program <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResource ViewResolver"> <property name="prefix" value="/WEBINF/output/"></property> <property name="suffix" value=".jsp"></property> </bean> <bean name="/start.htm" class="core.HelloController"> <property name="message" value="welcome to spring MVC"></property> </bean> Redirect.jsp--><%response.sendRedirect("start.htm");%> Controller --> Insider handleRequestInternal System.out.println("In Controller"); return new ModelAndView("View1","priyanka",message); 19] show the usage of FormController, Form Tags using Form Tags a) web.xml --> no change b) redirect.jsp --> registeruser.htm c) core-servlet.xml
Page 11 of 26

Venkat Krishnan -> http://evenkat.com

<bean id="viewResolver"--> same <bean name="/userregister.htm" class="core.UserController"> <property name="formView" value="input"/> --> GUI form <property name="successView" value="success"/> <property name="us" ref="uservice"/> </bean> <bean id="uservice" class="core.UserService"/> c1) class User --> String name, String password, gender, country, aboutYou, String [] community --> getter and setter methods d) class UserController extends SimpleFormController{ UserService us; --> setter public UserController(){ setCommandClass(User.class); setCommandName("POJO"); } public ModelAndView onSubmit(Object p) throws Exception{ User u = (User)p; us.persist(); return new ModelAndView("success","key",u); }} e) success.jsp Your name is ${key.name} your password is ${key.password} f) input.jsp <%@taglib uri="http://www.springframework.org/tags/form" prefix="f"%> <!DOCTYPE....> <html><body> <f:form method="post" commandName="POJO"> <pre> UserName: <f:input path="name"> password: <f:password path="password"> Gender: <f:radiobutton path="gender" value="Male" label="Male"> <f:radiobutton path="gender" value="Female" label="Female"> country:<f:select path="country">

Page 12 of 26

Venkat Krishnan -> http://evenkat.com

<f:option value="0" label="India"/><f:option value="1" label="USA"/><f:option value="2" label="UK"/> </f:select> About You<f:textarea path="aboutYou"> Community<f:checkbox path="community" value="Spring" label="Spring"> <input type=submit> g) interface UserService --> persist() h) class UserServiceImpl extends UserService persist (){SOP} 20]validation a) UserForm.jsp <head> <style type="text/css"> .error{color:red; font-style:italic; } </style></head><body><f:form method="post" commandName="POJO"> UserName: <f:input path="username"> <f:errors path=username cssClass="error"/> b) class UserValidator implements Validator --> override the supports method{ return User.class.isAssignableFrom(class); } private static final int MIN_LEN=6; public void validate(Object p, Errors err){ ValidationUtils.rejectIfEmptyOrWhitespace(err,"username","na me.req"); ValidationUtils.rejectIfEmptyOrWhitespace(err,"password","pas s.req"); User u1 = (User) p; if(u1.getPassword().length<MIN_LEN){ err.rejectValue("password","pass.len"); }} c) core-servlet.xml
Page 13 of 26

Venkat Krishnan -> http://evenkat.com

<bean id="uvalidator" class="core.UserValidator"> <bean name="/userregister.htm" class="core.UserController"> <property name="formView" value="input"/> --> GUI form <property name="successView" value="success"/> <property name="us" ref="uservice"/> <property name="validator" ref="uvalidator"/> </bean> <bean id="messageSource" --> page 153> <property name="basename" value="error"/> d) error.properties name.req=Name is Mandatory pass.req=Password is required pass.len=Minimum Number of char is 6 21] Spring Form tags using Annotations a) web.xml file b) core-servlet.xml <context:component-scan base-package="core"/> <bean id="viewResolver" /> c) redirect.jsp --> userannotation.htm d) @Controller @RequestMapping(value="/userannotation.htm") @SessionAttributes("user") class User Controller { @Autowired private UserService us; @RequestMapping(method=RequestMethod.GET) String showUserForm(ModelMap m){ User u = new User(); u.setUserName("Temp"); m.addAttribute(u); return "input"; } @RequestMapping(method=RequestMethod.POST) public String showOnSubmit(@ModelAttribute("user") User u)throws Exception { us.persist(u);return "success"; }//end of showOnSubmit
Page 14 of 26

Venkat Krishnan -> http://evenkat.com

}//end of Controller Variation of refresh on the final page a) in the POST Handler method return "redirect:any.htm" b) Create another controller called @Controller class UserSuccessController{ @RequestMapping(value="/any.htm", method=RequestMethod.GET) public string finalTest(){ SOP ("Called"); return "usersuccess"; } } With @ModelAttribute, you specify that an attribute you are passing to / receiving from a controller's method is "bound" to an attribute of your model. This annotation is at attribute level and it works in conjuction with Spring's form:form or spring:bind tags in the page. @SessionAttribute is used on a form lifecycle handling controller to specify which of the model attributes are to be bound to the session (so that they can be retrieved in subsequent requests that still concern the same controller, for example when you submit a form and a validation error occurs and you are taken back to the same form, with all the inputs you entered properly preserved. All the parameters and methods(return values) annotated with @ModelAttribute would be added to the model object to be used by the views for rendering the output. The @ModelAttribute applied on the method level would also be available for the handler methods (as parameters using @ModelAttribute on parameters). So, in a way they are request scoped. If you want any of these modelattributes to be added/retrieved to/from the session, then annotate the class with @SessionAttributes(modelattributename)
Page 15 of 26

Venkat Krishnan -> http://evenkat.com

22] Spring Validation using Annotations a) In the UserController class define UserValidator as a class variable. b) Define a constructor to UserController which takes UserService and UserValidator in its parameters and assigns the value to the class variable. use @Autowired above the constructor to do the injection c) In the onSubmit method define the second parameter called BindingResult br. d) in the body of onSubmit call the validate function and check for hasErrors of the br object with a if-else userValidator.validate(u, br); if(br.hasErrors()){return "userForm"; }else {return "redirect:usersuccess.htm";} 23] Spring Security a) web.xml JAR FILES REQUIRED: SECURITY CONFIG, CORE AND WEB <listener> <listenerclass>org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/mvc-dispatcher-servlet.xml, /WEB-INF/springsecurity.xml </param-value> </context-param> <filter> <filter-name>springSecurityFilterChain</filter-name> <filterclass>org.springframework.web.filter.DelegatingFilterProxy</filt er-class>
Page 16 of 26

Venkat Krishnan -> http://evenkat.com

</filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> b)spring-security.xml <http auto-config="true"> <intercept-url pattern="/welcome*" access="ROLE_USER" /> </http> <authentication-manager> <authentication-provider> <user-service> <user name="abc" password="123" authorities="ROLE_USER" /> </user-service> </authentication-provider> </authentication-manager> </beans:beans> c) Controller file @Controller @RequestMapping(value="/welcome") public class HelloController { @RequestMapping(method = RequestMethod.GET) public String printWelcome(ModelMap model) { model.addAttribute("message", "Spring Security hello"); return "hello"; }} 24] Spring JDBC transaction and jdbc jar files + database specific jar file 1] beans.xml <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDat aSource"> <property name="driverClassName" value="oracle.jdbc.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@localhost:1521:XE" ></property>
Page 17 of 26

Venkat Krishnan -> http://evenkat.com

<property name="username" value="system" /> <property name="password" value="admin" /> </bean> <bean id="stujdbc" class="core.StudentJdbcTemplate"> <property name="dataSource" ref="ds" /> </bean> 2] Create a Student POJO having sid as the primary key and name and age as attributes. Have getter and setter methods for all 3 and override toString to display all 3 attributes. 3] create a StudentDAO Interface public interface StudentDao { void setDataSource(DataSource ds); void create(String name, Integer age); List<Student> listStudents(); } 4] Create a implementation: public class StudentJdbcTemplate implements StudentDao { private DataSource ds; private JdbcTemplate jt; public void setDataSource(DataSource ds) { this.ds = ds; jt = new JdbcTemplate(ds); } public void create(String name, Integer age) { String sql = "INSERT INTO STUDENT VALUES(SEQUENCEID.NEXTVAL,?,?)"; int row = jt.update(sql, name, age); Sop("Student created"); } public List<Student> listStudents() { String q="SELECT * FROM STUDENT"; List<Student> s=jt.query(q, new StudentMapper()); return s; } 5] Create a Custom Mapper public class StudentMapper implements RowMapper<Student> { public Student mapRow(ResultSet rs, int r) throws SQLException { Student s1 = new Student(); s1.setId(rs.getInt("id")); s1.setName(rs.getString("name")); s1.setAge(rs.getInt("age"));
Page 18 of 26

Venkat Krishnan -> http://evenkat.com

return s1; }} 6] Create the Main ApplicationContext apx = new ClassPathXmlApplicationContext("beans.xml"); StudentJdbcTemplate s1=(StudentJdbcTemplate)apx.getBean("stujdbc"); s1.create("Anand", 24); s1.create("Ruksar",22); List<Student> l=s1.listStudents(); System.out.println(l); -----------------------------------------------CREATE SEQUENCE SEQUENCEID MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 10; -----------------------------------------------Variation:Student getStudent(Integer id); void updateAge(Integer age, Integer id); void delete(Integer id); Main make the necessary changes ================================================ ===== Spring Core AOP Spring MVC Spring Security Spring JDBC - CRUD 25] a) hibernate.cfg.xml - Page 7 hibernate-configuration connection.driver_class connection.url connection.username connection.password connection.pool_size 10 dialect">org.hibernate.dialect.OracleDialect</property>
Page 19 of 26

Venkat Krishnan -> http://evenkat.com

show_sql">true</property> hbm2ddl.auto">create</property> <mapping resource="Contact.hbm.xml"/> </session-factory> </hibernate-configuration> b) Contact.hbm.xml <!DOCTYPE page 66> <hibernate-mapping> <class name="core.Contact" table="CONTACTS"> <id name="id" type="integer" column="contactid"> <generator class="assigned"/> </id> <property name="fname" column = "ContactFName"/> <property name="lname" column = "ContactLName"/> </class> </hibernate-mapping> c) class Contact with Integer id, String fname, String lname and Getter and Setter methods d) HibernateUtil-copy it from Java Persistence book. page 91 e) Main PSVM--> SessionFactory sf = HibernateUtil.getSessionFactory(); Session ses =sf.openSession(); ses.beginTransaction(); Contact c = new Contact(); c.setId(1); c.setFname("A");c.setLname("B"); ses.save(c); ses.getTransaction().commit(); ses.flush();ses.close();HibernateUtil.shutdown(); f) jar file hibernate3.jar + all jars in required and JPA folder 26] CRUD - Course Example a) hibernate.cfg.xml --> hbm2ddl to update b) Course.hbm.xml --> generator to native c) Course Pojo -> courseid and coursename d) HibernateUtil e) Main methods --> Integer saveCourse(String name) --> listCourse() --> updateCourse(Integer id, String name) --> deleteCourse(Integer id)
Page 20 of 26

Venkat Krishnan -> http://evenkat.com

PSVM Main m = new Main(); Integer x1 = m.saveCourse("Maths"); Integer x2 = m.saveCourse("Biology"); Integer x3 = m.saveCourse("Physics"); m.listCourse(); m.updateCourse(x2,"Chemistry"); m.deleteCourse(x1); m.listCourse(); listCourse(){ List li=ses.createQuery("from Course").list(); for (Iterator i = li.iterator; i.hasNext();){ Course cc = (Course)i.next(); sop(cc.getCourseName()); } updateCourse(Integer i, String n){ Course c1 = (Course)ses.get(Course.class,i); c1.setCoursename(n); } deleteCourse(Integer i){ Course c2 = (Course)ses.get(Course.class,i); ses.delete(c2); } 27] a) Hibernate.cfg.xml --> <mapping class="core.Order"/> b) POJO - Order javax.persistence.* org.hibernate.* @Entity @Table(name="OrderDetails") public class Order{ private int oid; private String partyName; @Id @GeneratedValue @Column(name="order_id") public int getOid(){} @Column(name="Party_Name")
Page 21 of 26

Venkat Krishnan -> http://evenkat.com

public String getPartyName(){} write setter methods } c) HibernateUtil d) Main insert 2 orders 28] One-To-One using Annotation [Student --> Address] a) Student Integer sid, String sName, Address sAddress @Column(name="Student_Name", nullable=false, length=100) public String getSName() @OneToOne(cascade=CascadeType.ALL) public Address getAddress b) Address Integer aid, String city, String state c) Main Address a1 = new Address("Mumbai","MAH"); Address a2 = new Address("Kol","WB"); Student s1 = new Student("ABC",a1); Student s2 = new Student("XYZ",a2); ses.save(s1); ses.save(s2); 29] Many to One using XML file College-->1 Course--N c_id cs_id college_name course_name college_address course_category college_course --> 1 a) cfg.xml --> <mapping resource="College.hbm.xml"> Course also b) College.hbm.xml <h-m> <class name=core.College table="CollegeDetails"> <id name="c_id" type column> <generator > <property name="college_name" type="String" column> <property name="college_address">
Page 22 of 26

Venkat Krishnan -> http://evenkat.com

</class></h-m> c) Course.hbm.xml <h-m> <class> <id> <property name="course_name"> <property name="course_category"> <many-to-one name="college_course" class="core.College" cascade="all" not-null="true"/? </class> d) POJO - Course cs_id, course_name, course_category, College e) POJO - College f) Main College c = new College(); Course c1 = pass c Course c2 = pass c ses.save(c1); ses.save(c2); 30] One to Many using Annotation One Student having multiple Phones sid pid sname ptype pname Student_Phone Table sid pid a) hibernate.cfg.xml --> mapping class b) Student --> POJO @Entity @Table(name="StudentPhone") public class Student{ Integer sid; String sname Set<Phone> sphone = new HashSet<Phone>(); constructor with sname and a set @Id @GeneratedValue @Column public Integer getSid(){} setSid @Column public String getSname()
Page 23 of 26

Venkat Krishnan -> http://evenkat.com

setSname() @OneToMany(cascade=CascadeType.ALL) PageNo 159 @JoinTable(name="Student_Phone", joinColumns=( @JoinColumn(name="sid")), inverseJoinColumns=(@JoinColumn (name="pid")) ) public Set<Phone> getSphone() setSphone(); c) Phone -> POJO d) Main Set<Phone> pnos = new HashSet<Phone>(); pnos.add(new Phone) pnos.add(new Phone) Student s1 = new Student("ABC",pnos); ses.save(s1); In one to Many do not create 2 students 31] Many to Many using XML file with Student and Course NOTE: Please use setID and manually set the values for Course. keep generator to assigned in one. 32] Caching Techniques a] Session Cache: import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @Entity @Cacheable @Cache(usage=CacheConcurrencyStrategy.READ_ONL Y)// no writing of userdetails in to DB public class UserDetails { @Id @GeneratedValue private int userId; private String userName; } b] In Hibernate.cfg.xml <property name="hibernate.cache.use_second_level_cache">true</prope rty>

Page 24 of 26

Venkat Krishnan -> http://evenkat.com

<property name="hibernate.cache.provider_class">org.hibernate.cache.E hCacheProvider</property> --> make hbm2dll to create [just making it easy] c] In Main UserDetails u = new UserDetails(); u.setUserName("ABC"); ses.save(u);t.commit();ses.close(); UserDetails u1=(UserDetails) ses.get(UserDetails.class,1); System.out.println(u1.getUserName()+" u1 "); u1.setUserName("XYZ"); UserDetails u2=(UserDetails) ses.get(UserDetails.class,1); System.out.println(u2.getUserName()+" u1 "); [variation1] Session sess1 = sf.openSession(); UserDetails u3 = (UserDetails)sess1.get(UserDetails.class, 6); System.out.println(" u3 "+u3.getUserName()); System.out.println("-----------------------"); SessionFactory sf1 = new Configuration().configure().buildSessionFactory(); Session sess2 = sf1.openSession(); UserDetails u4 = (UserDetails)sess2.get(UserDetails.class, 6); System.out.println(" u3 "+u4.getUserName()); If you are using HibernateUtil.getSessionFactory,it will have only 1 select statement. [variation2] <property name="hibernate.cache.use_query_cache">true</property> SessionFactory sf = new Configuration().configure().buildSessionFactory(); Session sess = sf.openSession(); Query q = sess.createQuery("from UserDetails u where u.userId = 5");
Page 25 of 26

Venkat Krishnan -> http://evenkat.com

q.setCacheable(true); List l1 = q.list(); System.out.println(l1.size()); sess.close(); Session sess6 = sf.openSession(); Query q6 = sess6.createQuery("from UserDetails u where u.userId =5"); q6.setCacheable(true); List l2 = q6.list(); System.out.println(l2.size()); sess6.close(); venkatkrishnan@vsnl.net

Page 26 of 26

S-ar putea să vă placă și