Guest User

Untitled

a guest
Apr 8th, 2018
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.22 KB | None | 0 0
  1. import java.lang.Integer
  2. import com.novocode.squery._
  3. import com.novocode.squery.Implicit._
  4. import com.novocode.squery.session._
  5. import com.novocode.squery.session.SessionFactory._
  6.  
  7. // Define table:
  8. object Users extends Table[(Integer, String, String)]("users") {
  9. def id = intColumn("id", O.AutoInc, O.NotNull)
  10. def first = stringColumn("first")
  11. def last = stringColumn("last")
  12. def * = id ~ first ~ last
  13. }
  14.  
  15. // Basic usage
  16. val sf = new DriverManagerSessionFactory("org.h2.Driver", "jdbc:h2:mem:test1")
  17. sf withSession {
  18. // Prepare a simple query
  19. val q1 = for(u <- Users) yield u
  20.  
  21. // Print SQL statement to be executed:
  22. println(q1.selectStatement) // displays SELECT t1.id,t1.first,t1.last FROM users t1
  23.  
  24. // Print query result:
  25. for(t <- q1) println("User tuple: "+t)
  26.  
  27. // Query statements can also be used with updates:
  28. val q = for(u <- Users if u.id is 42) yield u.first ~ u.last
  29. q.update("foo", "bar")
  30. }
  31.  
  32. import com.twitter.querulous.evaluator.QueryEvaluator
  33. val queryEvaluator = QueryEvaluator("host", "username", "password")
  34. val users = queryEvaluator.select("SELECT * FROM users WHERE id IN (?) OR name = ?", List(1,2,3), "Jacques") { row =>
  35. new User(row.getInt("id"), row.getString("name"))
  36. }
  37. queryEvaluator.execute("INSERT INTO users VALUES (?, ?)", 1, "Jacques")
  38. queryEvaluator.transaction { transaction =>
  39. transaction.select("SELECT ... FOR UPDATE", ...)
  40. transaction.execute("INSERT INTO users VALUES (?, ?)", 1, "Jacques")
  41. transaction.execute("INSERT INTO users VALUES (?, ?)", 2, "Luc")
  42. }
  43.  
  44. // Defining tables and a schema:
  45. import org.squeryl.PrimitiveTypeMode._
  46.  
  47. class Author(var id: Long,
  48. var firstName: String,
  49. var lastName: String)
  50.  
  51. class Book(var id: Long,
  52. var title: String,
  53. @Column("AUTHOR_ID") // the default 'exact match' policy can be overriden
  54. var authorId: Long,
  55. var coAuthorId: Option[Long]) {
  56. def this() = this(0,"",0,Some(0L))
  57. }
  58.  
  59. object Library extends Schema {
  60. //When the table name doesn't match the class name, it is specified here :
  61. val authors = table[Author]("AUTHORS")
  62. val books = table[Book]
  63. }
  64.  
  65. // Basic usage
  66. Class.forName("org.postgresql.Driver");
  67. val session = Session.create(
  68. java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/squeryl", "squeryl", "squeryl"),
  69. new PostgreSqlAdapter
  70. )
  71.  
  72. //Squeryl database interaction must be done with a using block :
  73. import Library._
  74. using(session) {
  75. books.insert(new Author(1, "Michel","Folco"))
  76. val a = from(authors)(a=> where(a.lastName === "Folco") select(a))
  77. }
  78.  
  79. case class Song(id: Option[Long], title: String, seconds: Short)
  80. case class Album(id: Option[Long], title: String, year: Short, songs: IndexedSeq[Song])
  81. case class Artist(id: Option[Long], name: String, albums: Set[Album])
  82.  
  83. object SongExtractor extends JoinExtractor[Song] {
  84. val key = Set("SONG_ID")
  85.  
  86. def extract(row: Row, join: Join) = {
  87. new Song(
  88. row.bigInt("SONG_ID"),
  89. row.string("TITLE").get,
  90. row.smallInt("DURATION_SECONDS").get
  91. )
  92. }
  93. }
  94.  
  95. object AlbumExtractor extends JoinExtractor[Album] {
  96. val key = Set("ALBUM_ID")
  97.  
  98. def extract(row: Row, join: Join) = {
  99. new Album(
  100. row.bigInt("ALBUM_ID"),
  101. row.string("TITLE").get,
  102. row.smallInt("YEAR_ISSUED").get,
  103. join.extractSeq(SongExtractor, Map("TITLE"->"SONG_TITLE"))
  104. )
  105. }
  106. }
  107.  
  108. object ArtistExtractor extends JoinExtractor[Artist] {
  109. val key = Set("ARTIST_ID")
  110.  
  111. def extract(row: Row, join: Join) = {
  112. new Artist(
  113. row.bigInt("ARTIST_ID"),
  114. row.string("NAME"),
  115. join.extractSeq(AlbumExtractor)
  116. )
  117. }
  118. }
  119.  
  120. val ds: javax.sql.DataSource = ...
  121. val builder = new SQLFileBuilder(ds, new java.io.File("sql/"))
  122. val broker = builder.build()
  123.  
  124. // Print all artists with their albums (if any)
  125. val artists = broker.readOnly() { session =>
  126. session.selectAll[Artist]('selectArtist) // ' I wish they could fix the Scala Symbol formatting
  127. }
  128. for (ar <- artists) {
  129. println(a.name)
  130. if (ar.albums.isEmpty)
  131. println("t<No albums>")
  132. else for (al <- ar.albums) {
  133. println("t" + al.title)
  134. for (s <- al.songs) {
  135. println("tt" + (al.songs.indexOf(s)+1) + ". " + s.title)
  136. }
  137. }
  138. }
  139.  
  140. // Create an SQL query
  141. val selectCountries = SQL("Select * from Country")
  142.  
  143. // Transform the resulting Stream[Row] as a List[(String,String)]
  144. val countries = selectCountries().map(row =>
  145. row[String]("code") -> row[String]("name")
  146. ).toList
  147.  
  148. val countries = SQL("Select name,population from Country")().collect {
  149. case Row("France", _) => France()
  150. case Row(name:String, pop:Int) if(pop > 1000000) => BigCountry(name)
  151. case Row(name:String, _) => SmallCountry(name)
  152. }
  153.  
  154. SQL(
  155. """
  156. select * from Country c
  157. join CountryLanguage l on l.CountryCode = c.Code
  158. where c.code = {countryCode};
  159. """
  160. ).on("countryCode" -> "FRA")
  161.  
  162. class Category extends Record[Category] {
  163. val id = field(Category.id)
  164. val name = field(Category.name)
  165. val books = oneToMany(Book.category) // allows navigating between associations transparently
  166. }
  167.  
  168. object Category extends Table[Category] with LongIdPK[Category] {
  169. val name = stringColumn("name") // creates a column
  170. .notNull // creates NOT NULL constraint
  171. .unique // creates UNIQUE constraint
  172. .validateNotEmpty // adds NotEmpty validation
  173. .validatePattern("^[a-zA-Z]{1,8}$") // adds Pattern validation
  174. }
  175.  
  176. class Book extends Record[Book] {
  177. val id = field(Book.id)
  178. val title = field(Book.title)
  179. val category = manyToOne(Book.category)
  180. }
  181.  
  182. object Book extends Table[Book] with LongIdPK[Book] {
  183. val title = stringColumn("title")
  184. .notNull
  185. .validateNotEmpty
  186. val category = longColumn("category_id")
  187. .references(Category) // creates an association with Category
  188. .onDeleteSetNull // specifies a foreign-key action
  189. .onUpdateCascade
  190. }
  191.  
  192. new DDLExport(Category, Book).create // creates database schema
  193.  
  194. // find category by id
  195. val c = Category.get(2l)
  196. // find all books
  197. val allBooks = Book.all
  198. // find books for category
  199. val cBooks = c.get.books
  200. // find books by title
  201. Book.criteria.add("title" like "a%").list
  202.  
  203. select()
  204. .from(Category as "c" join (Book as "b"), Category as "c1")
  205. .where("c1.name" like "a%")
  206. .addOrder(asc("c.name"))
  207. .list
  208.  
  209. select(count("b.id"), "c.name").from(Category as "c" join (Book as "b")).list
  210.  
  211. import java.util.{List => JList}
  212.  
  213. val jdbcTemplate = new SimpleJdbcTemplate(dataSource)
  214. val sql = "select name, age from my_obj"
  215. val os: JList[MyObj] = jdbcTemplate.query(sql, new ParametrizedRowMapper[MyObj] {
  216. def mapRow(rs: ResultSet, row: Int) : MyObj = {
  217. //convert a row of a result set to a MyObj
  218. MyObj(rs.getString("name"), rs.getInt("age"))
  219. }
  220. }
  221.  
  222. class MyClass extends Something
  223. with SimpleEntityManagerFactory
  224. with ThreadLocalEntityManager {
  225.  
  226. def getPersistenceUnitName = "mip"
  227. . . .
  228. }
  229.  
  230. @Entity
  231. @Table(name = "obj_item")
  232. @Inheritance(strategy = InheritanceType.JOINED)
  233. @SequenceGenerator(name = "obj_item_id_seq", sequenceName = "obj_item_id_sequence", allocationSize = 1)
  234. class ObjectItem extends MIPEntity {
  235. @Id
  236. @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "obj_item_id_seq")
  237. @Column(name = "obj_item_id", nullable = false, length = 20)
  238. @BeanProperty
  239. var id: BigInteger = _
  240.  
  241. @Column(name = "cat_code", nullable = false, length = 6)
  242. @BeanProperty
  243. var objItemCatCode: String = _
  244. }
  245.  
  246. @Entity
  247. @Table(name = "org_struct")
  248. @IdClass(classOf[OrganisationStructureId])
  249. @SequenceGenerator(name = "org_struct_index_seq", sequenceName = "org_struct_index_sequence", allocationSize = 1)
  250. class OrganisationStructure extends MIPEntity {
  251. @Id
  252. @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "org_struct_index_seq")
  253. @Column(name = "org_struct_ix", nullable = false, length = 20)
  254. @BeanProperty
  255. protected var ix: BigInteger = _
  256.  
  257. @Id
  258. @ManyToOne(fetch = FetchType.EAGER)
  259. @JoinColumn(name = "org_struct_root_org_id", nullable = false, updatable = false)
  260. @BeanProperty
  261. protected var orgStructRootOrg: Organisation = _
  262.  
  263. . . .
  264. }
  265.  
  266. class OrganisationStructureId {
  267. @BeanProperty
  268. var orgStructRootOrg: BigInteger = _
  269. @BeanProperty
  270. var ix: BigInteger = _
  271. . . .
  272. }
  273.  
  274. . . .
  275. val filter: NameFilter = newFilterInstance(QueryId("FindObjectItemFromNameWithFilter"))
  276. filter.name = "%Test%"
  277.  
  278. var i = 0
  279. forQueryResults {
  280. oi: ObjectItem =>
  281. i = i + 1
  282. } withQuery (filter)
  283. i must_== 10
  284. . . .
  285.  
  286. withTrxAndCommit {
  287. findAndApply(id ) {
  288. u:User => remove(u)
  289. }
  290. }
  291.  
  292. withTrxAndCommit {
  293. oneResultQueryAndApply {
  294. d: Double =>
  295. eStatRet.setDistance(d)
  296. } withNativeQuery (QueryId("DistancePointFromTextToLocID"), postGISPoint, user.getUsersLocation.getId)
  297. }
  298.  
  299. class Product(val name: String, val attributes: Set[Attribute])
  300. class Attribute(val name: String, val value: String)
  301. ...
  302.  
  303. val product = new Product("blue jean", Set(new Attribute("colour", "blue"), new Attribute("size", "medium")))
  304. val inserted = mapperDao.insert(ProductEntity, product)
  305. // the persisted entity has an id property:
  306. println("%d : %s".format(inserted.id,inserted))
  307.  
  308. val o=OrderEntity
  309.  
  310. import Query._
  311. val orders = query(select from o where o.totalAmount >= 20.0 and o.totalAmount <= 30.0)
  312. println(orders) // a list of orders
  313.  
  314. import java.sql.{Connection, DriverManager, ResultSet};
  315.  
  316. // Change to Your Database Config
  317. val conn_str = "jdbc:mysql:/localhost:3306/DBNAME?user=DBUSER&password=DBPWD"
  318.  
  319. // Load the driver
  320. classOf[com.mysql.jdbc.Driver]
  321.  
  322. // Setup the connection
  323. val conn = DriverManager.getConnection(conn_str)
  324. try {
  325. // Configure to be Read Only
  326. val statement = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
  327.  
  328. // Execute Query
  329. val rs = statement.executeQuery("SELECT quote FROM quotes LIMIT 5")
  330.  
  331. // Iterate Over ResultSet
  332. while (rs.next) {
  333. println(rs.getString("quote"))
  334. }
  335. }
  336. finally {
  337. conn.close
  338. }
  339.  
  340. # dbhost(s), dbname, username, password, urlOptions, driverName
  341. val queryEvaluator = QueryEvaluator("host", "dbname", "username", "password", Map[String,String](), "jdbc:postgresql")
  342.  
  343. val pe=PersonEntity //alias
  344. val people=query(QueryConfig.pagination(2, 10),select from pe where pe.lives === house)
Add Comment
Please, Sign In to add comment